/**
 * 定义表单itfreer.form.core模块
 * 包括tab选项，控件，权限等管理
 */
(function(window, angular, undefined){
	/* 
	 * 定义表单的核心模块
	 */
	var itfreerformcoreModule = angular.module('itfreer.form.core', ['itfreer.core']);

	/**
	 * 定义表单变量
	 */
	itfreerformcoreModule.value('$formObject',{
		/**
		 * tab选项卡管理
		 */
		tabs : {},
		/**
		 * 菜单选项卡管理
		 */
		menuClass : {},
		/**
		 * 默认表单
		 */
		df : {
			/**
			 * 表单的主表名称
			 */
			tableName : '',
			/**
			 * 表单的主健，只能为一个，一般为GUID字段
			 */
			keyField : '', 	
			/**
			 * 表单所绑定的工作流ID
			 */
			bmpKey 	: '',
			/**
			 * 表单需要随机赋值的字段
			 */
			randomFields : '',
			/**
			 * 表单默认值
			 */
			defaultObject : {},
			/**
			 * 主表的默认的查询值
			 */
			queryValue : {},
			 /**
			 * 主表的排序对象
			 */
			orderObject : {},
			/**
			 * 表单中treeGird控件名称
			 */	
			treeGirdName : '',
			/**
			 * 表单中treeGrid的idField
			 */	
			idField : '',
			/**
			 * 表单中treeGrid的PIDField
			 */	
			pIDField : '',
			/**
			 * 表单中treeGrid的默认加载级别
			 */
			treeLoadJBs : '',
			/**
			 * 表单中treeGrid的树级别字段
			 */
			treeJBField : '',
			/**
			 * 表单中treeGrid的树是否叶子节点字段
			 */
			treeIsChildField : '',
			/**
			 * 主表单的列表数据
			 */
			editList : {
				/**
				 * 数据列表
				 */
				list : null,
				/**
				 * 当前选择的行
				 */
				checkedRow : null,
				/**
				 * 当前选择的行集合
				 */
				checkedRows : null,
				/**
				 * 分页大小
				 */
				pageSize : 15,
				/**
				 * 分页索引
				 */
				pageIndex : 1,
				/**
				 * 页数
				 */
				pageCount : 0,
				/**
				 * 分页对象列表(1,2,3)
				 */
				pageList: [1],
				/**
				 * 总的条数
				 */
				rowsCount: 0
			}, 
			/**
			 * 主表单当前编辑对象
			 */
			editRow : null,
			/**
			 * 主表单当前编辑对象的复制对象，用于解决编辑中的结果处理
			 */
			curOldRow : null,
			/**
			 * 一级子表的当前编辑记录
			 */
			cEditRow : null,
			/**
			 * 一级子表的当前编辑记录的复制对象
			 */	
			cOldRow : null,
			/**
			 * 主表的查询变量
			 */
			queryObject : null,
			/**
			 * 主表的查询变量的复制对象
			 */
			oldQueryObject : null,
			/**
			 * 主表的定义当前工作流的表单配置信息
			 */
			bpmFormList : null,
			/**
			 * 主表的当前工作流当前任务的表单配置信息
			 */
			bpm : null,
			/* 
			 * 是事为MIS视图
			 */
			isMIS : true
		},

		/**
		 * 当前注册的表单名称，单页
		 */
		formNames : [],

		/**
		 * easy ui window窗口的收集器，用于对象删除
		 */
		windows : [],

		/**
		 * easy ui combotree
		 */
		combotrees : [],

		/**
		 * easy ui combobox
		 */
		comboboxs : [],

		/**
		 * easy ui treegrid
		 */
		treegrids : [],

		/**
		 * easy ui Datebox
		 */
		dateboxs : [],
		/**
		 * easy ui datetimeboxs
		 */
		datetimeboxs : [],
		/**
		 * 审批历史记录
		 */
		historyRow : [],
		/**
		 * 定义工作流下一节点的审批人信息
		 */
		nextAssignees : [],
		/**
		 * 定义汇签情况下，提交那个任务节点
		 */
		nextTasks : [],
		/**
		 * 流程交办的用户编号与名称
		 */
		bpmJb : {},

		/**
		 * 处理权限安全控制
		 */
		si : {},
		/**
		 * 用户
		 */
		user : {},

		/**
		 * 对象是否为新对象判断值
		 */
		isNew : "FIELD_ISNEW",
		 /**
		 * 新增的对象选择字段属性
		 */
		selectedField : "selected",
		/**
		 * 密码修改对象
		 */
		password : {},

		/**
		 * 是否异步操作中(如：保存，删除，取子表等)
		 */
		isOptioning : false
	});

	/**
	 * 定义核心模块服务，定义数据查询方法
	 */
	itfreerformcoreModule.factory('$itfreerHttp', function($rootScope, $state, 
		$formObject, $itfreer_core) {
		var sessionId = $("#_sessionid").html();
		var $itfreerHttp = {
			/**
			 * 保存单个对象，row为js对象
			 */
			save : function(tableName, row, onsucess, onerror) {
				var args = { data : row };
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/save.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : function(data,textStatus,jqXHR){
						if(onsucess){
							onsucess(data);
						}
					},
					error: function(jqXHR,textStatus,errorThrown){
						if(onerror){
							onerror(jqXHR,textStatus,errorThrown);
						}else{
							$.messager.alert("错误",jqXHR.responseText,"error");
						}
					}
				});
			},

			/**
			 * 保存多个对象，rows为js数组对象
			 */
			saveList : function(tableName, rows, callback, onerror) {
				var args = {
					data : rows
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/saveList.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 删除数据，根据数据行，row为数据行条件，json对象
			 */
			deleteByKeyInBpm : function(tableName, row, activitiKey, callback, onerror) {
				var args = {
					data : row,
					akey : activitiKey
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/deleteByKeyInBpm.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 删除数据，根据数据行，row为数据行条件，json对象
			 */
			deleteByKey : function(tableName, row, callback, onerror) {
				var args = {
					data : row
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/deleteByKey.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取对象根据主键
			 */
			getEntityByKey : function(tableName, key, callback, onerror) {
				var args = {
					data : key
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getEntityByKey.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取数据行根据分页条件，query：查询条件，Map对象，Json格式；order：排序条件，Map对象，Json格式
			 */
			getPageRows : function(tableName, query, order, pageSize, pageIndex, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pageSizeData : pageSize,
					pageIndexData : pageIndex,
					sessionId:sessionId
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getPageRows.do',
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取数据行根据分页条件，query：查询条件，Map对象，Json格式；order：排序条件，Map对象，Json格式
			 */
			getTreeData : function(tableName, query, order, pId, jbs, domainname, pageSize, pageIndex, useCache, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pID : pId,
					JBs : jbs,
					domainName:domainname,
					pageSizeData : pageSize,
					pageIndexData : pageIndex
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				
				var typeString = "POST";
				if(useCache){
					typeString = "GET";
				}
				
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getTreeData.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取字典值 ，使用GET方法，并使用缓存
			 */
			getDomains : function(tableName, domainName, filter, addPinYin, callback, onerror) {
				filter = filter ? $itfreer_core.toJSONStr(filter) : '';
				var args = {
					data : domainName,
					filterObject : filter,
					addPinYin : addPinYin
				};
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getDomains.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			}, 

			/**
			 * 获取字典值
			 */
			getDomainsEx : function(tableName, domainName, cStatic, callback, onerror) {
				var args = {
					data : domainName,
					convertStatic : cStatic
				};
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getDomainsEx.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildData : function(tableName, row, childTablesString, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildData.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildDataEx : function(tableName, row, childTablesString, childOrdersString, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString,
					childOrders : childOrdersString
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildDataEx.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取子表数据
			 */
			getChildDataEx2 : function(tableName, row, childTablesString, childOrdersString, tagetTableNames, callback, onerror) {
				var args = {
					data : row,
					childTables : childTablesString,
					childOrders : childOrdersString,
					tagetTableNames : tagetTableNames
				};
				args.data = $itfreer_core.toJSONStr(args.data);
				$.ajax({
					url : getBasePath()+'/form/' + tableName + '/getChildDataEx2.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 导出doc
			 */
			exportDoc : function(dataMap, flt, fileName, callback, onerror){
				var args = { dataMap : dataMap, flt : flt, fileName : fileName };
				args.dataMap = $itfreer_core.toJSONStr(args.dataMap);
				$.ajax({
					url : getBasePath()+'/word/export.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 导出Excel
			 */
			exportExcel : function(tableName,exportInfo,moduleName,fileName,template,queryFields,displayFields,whereString,orderByString,selectFields,groupByString,whereParameter,isNullHeJi,callback,onerror){
				var args = {
					tableName : tableName,
					exportInfo : $itfreer_core.toJSONStr(exportInfo),
					moduleName : moduleName,
					fileName : fileName,
					template : template,
					queryFields : queryFields,
					displayFields : displayFields,
					whereString : $itfreer_core.toJSONStr(whereString),
					orderByString : $itfreer_core.toJSONStr(orderByString),
					selectFields : $itfreer_core.toJSONStr(selectFields),
					groupByString : $itfreer_core.toJSONStr(groupByString),
					whereParameter : $itfreer_core.toJSONStr(whereParameter),
					isNullHeJi : isNullHeJi
				}
				$.ajax({
					url : getBasePath()+'/excel/export.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 清除角色缓存
			 */
			clearRoleCache : function(callback, onerror) {
				var args = {};
				$.ajax({
					url : getBasePath()+'/role/clearcache.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 清除工作日设置缓存
			 */
			clearWorkDayCache : function(callback, onerror) {
				var args = {};
				$.ajax({
					url : getBasePath()+'/workDay/clearWorkDayCache.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 停止使用角色委托
			 */
			enableRoleWt : function(key, callback, onerror) {
				var args = { rowKey : key };
				args.rowKey = $itfreer_core.toJSONStr(args.rowKey);
				$.ajax({
					url : getBasePath()+'/role/enable.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 重新加载委托
			 */
			reloadWt : function(key, callback, onerror) {
				var args = { rowKey : key };
				args.rowKey = $itfreer_core.toJSONStr(args.rowKey);
				$.ajax({
					url : getBasePath()+'/role/reloadWt.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 保存密码
			 */
			savePassword : function(oldPW, newPW, rnewPW, callback, onerror) {
				var args = {
						oldPW : oldPW,
						newPW : newPW,
						rnewPW : rnewPW
				};
				$.ajax({
					url : getBasePath()+'/safe/password.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 设置地图的默认配置
			 */
			setDefulatConfig : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/gis/defulatconfig.do?sessionId='+sessionId,
					type: 'POST',
					data: null,
					timeout : 50000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 获取表字段数据
			 */
			getTableFields : function(tablename, callback, onerror) {
				var args = {
					tableName : tablename
				};
				$.ajax({
					url : getBasePath()+'/builder/getTableFields.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 构建表单
			 */
			builder : function(formID, callback, onerror){
				var args = { formid : formID };
				$.ajax({
					url : getBasePath()+'/builder/builder.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 构建所有数据表
			 */
			builderTables : function(jarName, ptah, callback, onerror){
				var args = { JarName : jarName, ptah : ptah };
				$.ajax({
					url : getBasePath()+'/builder/builderTables.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 构建数据表
			 */
			builderTable : function(id, JarName, ptah, callback, onerror){
				var args = { table : id, JarName : JarName, ptah : ptah };
				$.ajax({
					url : getBasePath()+'/builder/builderTable.do?sessionId='+sessionId,
					type: 'POST',
					data: args,
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 加载所有数据表
			 */
			initBaseTables : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/builder/getBaseTables.do?sessionId='+sessionId,
					type: 'POST',
					timeout : 35000,
					dataType: 'json',
					success: callback,
					error: onerror
				});
			},

			/**
			 * 流程图
			 */
			getBpmImage : function(exeId, callback, onerror) {
				var args = { executionId : exeId };
				args.executionId = $itfreer_core.toJSONStr(args.executionId);
				$.ajax({
					url : getBasePath()+'/workflow/exeimage.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'text',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获审批历史
			 */
			getBpmHistory : function(exeId, callback, onerror) {
				var args = { executionId : exeId };
				args.executionId = $itfreer_core.toJSONStr(args.executionId);
				$.ajax({
					url : getBasePath()+'/workflow/history.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取表单配置
			 */
			getBpmForm : function(dId, tId, callback, onerror) {
				var args = { definitionId : dId, taskId : tId };
				args.definitionId = $itfreer_core.toJSONStr(args.definitionId);
				args.taskId = $itfreer_core.toJSONStr(args.taskId);
				$.ajax({
					url : getBasePath()+'/workflow/form.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取所有表单配置
			 */
			getBpmForms : function(dId, callback, onerror) {
				var args = { definitionId : dId };
				args.definitionId = $itfreer_core.toJSONStr(args.definitionId);
				$.ajax({
					url : getBasePath()+'/workflow/forms.do?sessionId='+sessionId,
					type : 'GET',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 获取所有表单配置
			 */
			getWorkList : function(query, order, pageSize, pageIndex, getAllCount, refresRowCount, callback, onerror) {
				var args = {
					queryData : query,
					orderData : order,
					pageSizeData : pageSize,
					pageIndexData : pageIndex,
					getAllCount : getAllCount,
					refresRowCount : refresRowCount
				};
				args.queryData = $itfreer_core.toJSONStr(args.queryData);
				args.orderData = $itfreer_core.toJSONStr(args.orderData);
				$.ajax({
					url : getBasePath()+'/workflow/worklist.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},
			
			/**
			 * 自动构建流程配置
			 */
			autoSaveTask : function(pdId, callback, onerror) {
				var args = {
						processDefinitionId : pdId
				};
				$.ajax({
					url : getBasePath()+'/workflow/autoSaveTask.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 挂起或者激活流程定义
			 */
			suspendOrActivateByBpm : function(pdId, type, callback, onerror) {
				var args = {
					processDefinitionId : pdId,
					type : type
				};
				$.ajax({
					url : getBasePath()+'/workflow/suspendOrActivateDef.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 挂起或者激活流程实例
			 */
			suspendOrActivateByInst : function(instId, type, businessId, callback, onerror) {
				var args = {
					processInstanceId : instId,
					type : type,
					businessId : businessId
				};
				$.ajax({
					url : getBasePath()+'/workflow/suspendOrActivateInst.do?sessionId='+sessionId,
					type : 'POST',
					data : args,
					timeout : 35000,
					dataType : 'json',
					success : callback,
					error : onerror
				});
			},

			/**
			 * 设置地图的默认配置
			 */
			setDefulatConfig : function(callback, onerror){
				$.ajax({
					url : getBasePath()+'/gis/defulatconfig.do?sessionId='+sessionId,
					type: 'POST',
					data: null,
					timeout : 50000,
					dataType: 'text',
					success: callback,
					error: onerror
				});
			}
		};
		return $itfreerHttp;
	});

	/**
	 * 定义核心模块服务
	 */
	itfreerformcoreModule.factory('$itfreer_form_core', 
		function($rootScope, $state, $formObject, $itfreerHttp, $itfreer_core) {
		var sessionId = $("#_sessionid").html();
		var $itfreer_form_core = {

			// //打印插件地址
			urls : {
				lodopPlugin64 : "../style/script/lodop/iinstall_lodop6.194.64.exe",
				lodopPlugin32 : "../style/script/lodop/install_lodop6.194.32.exe"
			},

			/**
			 * 获取lodop打印对象
			 */
			getLodop : function () {
				//lodop打印
				var lodop = navigator.appVersion.indexOf("MSIE") >= 0 ? 
					document.getElementById('LODOP_OB') :
					document.getElementById('LODOP_EM');
				if(!lodop || !lodop.VERSION || lodop.VERSION < "6.1.4.5")
					return null;
				return lodop;
			},
			
			/**
			 * 设置默认的VIEW名称
			 */
			setDefulatUiView : function(viewName){
				var  topMenu = $("li[top_menu][ui-sref]");
				for(var i=0;i<topMenu.length;i++){
					var uiSelf = topMenu.attr("ui-sref");
					if(uiSelf){
						$state.go(uiSelf);
					}
					return;
				}
				$state.go(viewName);
			},

			/**
			 * 初始化tabs
			 */
			iniTab : function(tabName, tabItemNames, className){
				className = className ? className : 'selected';
				$formObject.tabs[tabName] = {};
				$formObject.tabs[tabName].className = className;
				$formObject.tabs[tabName].tabShow = {};
				$formObject.tabs[tabName].tabClass = {};
				
				var tNames = tabItemNames.split(",");
				tNames.forEach(function(item){
					$formObject.tabs[tabName].tabShow[item] = true;
					$formObject.tabs[tabName].tabClass[item] = className;
				});
			},

			/**
			 * 设置tabs的显示
			 */
			setTab : function(tabName, itemName){
				var items = itemName.split(',');
				if(!$formObject.tabs[tabName]){
					if(items.length>=1){
						$forestar_form_core.iniTab(tabName, items[0]);
					}else{
						$forestar_form_core.iniTab(tabName, items);
					}
				}
				if(items.length>1){
					items.forEach(function(e){
						$formObject.tabs[tabName].tabShow[e] = !$formObject.tabs[tabName].tabShow[e];
						if($formObject.tabs[tabName].tabShow[e]){
							$formObject.tabs[tabName].tabClass[e] = $formObject.tabs[tabName].className;
						}else{
							$formObject.tabs[tabName].tabClass[e] = "";
						}
					});
				}else{
					for(attribute in $formObject.tabs[tabName].tabShow){
						$formObject.tabs[tabName].tabShow[attribute] = false;
						$formObject.tabs[tabName].tabClass[attribute] = "";
					}
					$formObject.tabs[tabName].tabShow[itemName] = true;
					$formObject.tabs[tabName].tabClass[itemName] = $formObject.tabs[tabName].className;
				}
			},
			
			/**
			 * 初始化menuClass
			 */
			initMenuClass : function(classname){
				classname = classname ? classname : 'selected';
				//设置或获取对象指定的文件名或路径。
				var menu = window.location.pathname;
				$formObject.menuClass[menu] = classname;
			},

			/**
			 * 初始化当前用户和权限信息
			 */
			initSecurity:function(){
				var tags = $itfreer_core.getCookie("security_tag");
				$formObject.user.userid = $itfreer_core.getCookie("userid");
				$formObject.user.userrealname = decodeURI(escape($itfreer_core.getCookie("username")));
				$formObject.user.userdw = decodeURI(escape($itfreer_core.getCookie("userdw")));
				$formObject.user.dept = decodeURI(escape($itfreer_core.getCookie("deptname")));
				$formObject.user.userorg = decodeURI(escape($itfreer_core.getCookie("userorg")));
				$formObject.user.orgbh = decodeURI(escape($itfreer_core.getCookie("orgbh")));

				if(tags!=null){
					var tagList = tags.split(",");
					tagList.forEach(function(item){
						if(item.substring(0,1)=='"'){
							var sItem = item.substring(1,item.length);
							$formObject.si[sItem]=true;
						}else if(item.substr(item.length-1,1)=='"'){
							var sItem = item.substr(0,item.length-1);
							$formObject.si[sItem]=true;
						}else{
							$formObject.si[item]=true;
						}
					});
				}
			},

			/**
			 * 初始化table下表单属性
			 * 
			 * formName			表单名称
			 * tableName 		表单的主表名称
			 * keyField 		表单的主健，只能为一个，一般为GUID字段
			 * randomFields		表单需要随机赋值的字段
			 * orderObject 		主表的排序对象
			 * formValue		表单默认值
			 * queryValue 		主表的默认的查询值
			 * bmpKey 			表单所绑定的工作流ID
			 * pageSize			分页加载的分页数
			 * childTables
			 * childGridPara
			 * tagetTableNames
			 * childOrders
			 */
			initTablePara : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, pageSize,
					childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				$formObject.formNames.push(formName);
				$formObject[formName] = {};
				$formObject[formName].tableName = tableName;
				$formObject[formName].keyField = keyField;
				//随机赋值字段
				if (randomFields && randomFields!="") {
					$formObject[formName].randomFields = randomFields.split(',');
				}else{
					$formObject[formName].randomFields = [];
				}
				$formObject[formName].orderObject = orderObject;
				$formObject[formName].defaultObject = formValue;
				$formObject[formName].queryValue = queryValue;
				$formObject[formName].bmpKey = bpmKey;
				$formObject[formName].editList = {};
				$formObject[formName].editList.pageSize = pageSize ? pageSize : 20;
				$formObject[formName].editList.pageIndex = 1;
				$formObject[formName].editList.pageList = [];
				$formObject[formName].editList.pageList.push(1);
				$formObject[formName].queryObject = {};
				
				$formObject[formName].childTables = childTables;
				$formObject[formName].childGridPara = childGridPara;
				$formObject[formName].tagetTableNames = tagetTableNames;
				$formObject[formName].childOrders = childOrders;
			},

			// 初始化treeGrid下表单属性
			// formName			表单名称
			// tableName 		表单的主表名称
			// keyField 		表单的主健，只能为一个，一般为GUID字段
			// randomFields		表单需要随机赋值的字段
			// orderObject 		主表的排序对象
			// formValue		表单默认值
			// queryValue 		主表的默认的查询值
			// bmpKey 			表单所绑定的工作流ID
			// treeGirdName		树Grid的名称
			// idField			ID字段
			// pIDField			PID这段
			// treeJBField		树级别字段
			// treeIsChildField	树是否叶子节点字段
			// treeLoadJBs		树级别字段
			initTreePara : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, 
					treeGirdName, idField, pIDField, treeJBField, 
					treeIsChildField, treeLoadJBs,
					childTables, childGridPara, tagetTableNames, childOrders){

				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTablePara(formName, tableName, keyField, randomFields, 
						orderObject, formValue, queryValue, bpmKey, null, 
						childTables, childGridPara, tagetTableNames, childOrders);
				$formObject[formName].idField = idField;
				$formObject[formName].pIDField = pIDField;
				// 树级别字段
				$formObject[formName].treeJBField = treeJBField;
				// 树是否叶子节点字段
				$formObject[formName].treeIsChildField = treeIsChildField;
				$formObject[formName].treeGirdName = treeGirdName;
				$formObject[formName].treeLoadJBs = treeLoadJBs;
			},

			// 初始化表单属性并加载数据
			initAndLoadData : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bpmKey, pageSize, addResult,
					childTables, childGridPara, tagetTableNames, childOrders, loadScureess){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTablePara(formName, tableName, keyField, randomFields, 
						orderObject, formValue, queryValue, bpmKey, pageSize,
						childTables, childGridPara, tagetTableNames, childOrders);
				$itfreer_form_core.loadData(formName, true, addResult, loadScureess);
				if(bpmKey){
					$itfreer_form_core.loadBpmFormConfig(formName);
				}
			},

			// 数据分页加载 formName:表单名称，getRowCount:分页时是否计算所有数据记录数, addResult:是否添加查询结果到当前的结果集中，默认为false
			loadData : function(formName, getRowCount, addResult, loadScureess){
				formName = formName ? formName : 'fd';
				if(!$formObject[formName] || !$formObject[formName].tableName){
					return;
				}
				addResult = addResult ? addResult : false;
				getRowCount = getRowCount ? getRowCount : true;
				if(addResult){
					if(!objEquals($formObject[formName].oldQueryObject, $formObject[formName].queryObject)){
						$formObject[formName].oldQueryObject = jQuery.extend(true, {}, $formObject[formName].queryObject);
						addResult = false;
					}
				}
				$formObject[formName].editList.pageIndex = $formObject[formName].editList.pageIndex ? $formObject[formName].editList.pageIndex : 1;
				$itfreer_form_core.innerLoadData(formName, getRowCount, addResult, loadScureess);
			},
			
			// 数据分页加载 formName:表单名称，getRowCount:分页时是否计算所有数据记录数, addResult:是否添加查询结果到当前的结果集中，默认为false，loadScureess：加载成功
			// 目前还有分页加载数据时总计算数据总数的问题
			innerLoadData : function(formName, getRowCount, addResult, loadScureess){
				formName = formName ? formName : 'fd';
				addResult = addResult ? addResult : false;
				getRowCount = getRowCount ? getRowCount : true;
				
				var queryObject = jQuery.extend(true, $formObject[formName].queryObject, $formObject[formName].queryValue);
				var rowCount = $formObject[formName].editList.rowsCount ? $formObject[formName].editList.rowsCount : 0;
				
				$itfreerHttp.getPageRows($formObject[formName].tableName, queryObject , $formObject[formName].orderObject,
						$formObject[formName].editList.pageSize, $formObject[formName].editList.pageIndex,
					function(data){
						$rootScope.$apply(function() {
							if(!data){
								data = {};
								data.data = [];
								data.pageInfo = {};
								data.pageInfo.pageCount = 1;
								data.pageInfo.rowCount = 0;
							}
							
							$formObject[formName].editList.checkedRow=null;
							$formObject[formName].editList.checkedRows=[];
							
							$formObject[formName].editList.pageCount = data["pageInfo"]["pageCount"];
							$formObject[formName].editList.pageList = [];
							if($formObject[formName].editList.pageCount!=null && $formObject[formName].editList.pageCount!=99999999){
								for(var i=1;i<=$formObject[formName].editList.pageCount;i++){
									$formObject[formName].editList.pageList.push(i);
								}
							}else{
								$formObject[formName].editList.pageList.push(1);
							}

							$formObject[formName].editList.rowsCount = data["pageInfo"]["rowCount"];
							var dataList = data["data"] == null ? [] : data["data"];
							if(addResult){
								dataList.forEach(function(e){
									$formObject[formName].editList.list.push(e);
								});
							}else{
								$formObject[formName].editList.list = dataList;
							}

							if(loadScureess){
								loadScureess(formName, $formObject[formName].editList.list);
							}
						});
					}, 
					function(xhr){
					}
				);
			},
			
			// 设置查询条件并查询
			setQueryObjectAndQuery : function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].queryObject.hasOwnProperty(field)){
						delete $formObject[formName].queryObject[field];
					}
				}else{
					$formObject[formName].queryObject[field]=value;
				}
				$itfreer_form_core.loadData(formName, true, false);
			},
			
			// 设置排序对象
			setOrderObjectAndQuery : function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].orderObject.hasOwnProperty(field)){
						delete $formObject[formName].orderObject[field];
					}
				}else{
					$formObject[formName].orderObject[field]=value;
				}
				$itfreer_form_core.loadData(formName, true, false);
			},
			
			// 设置分页索引并且重新查询数据
			setPageIndexAndQuery : function(formName, pageIndex, addResult){
				formName = formName ? formName : 'fd';
				$formObject[formName].editList.pageIndex = pageIndex;
				$itfreer_form_core.loadData(formName, false, addResult);
			},
			
			//上一页
			prePage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				pageIndex--;
				if(pageIndex<=0){
					pageIndex =1 ;
				}
				$itfreer_form_core.setPageIndexAndQuery(formName, pageIndex, addResult);
			},
			
			//下一页
			nextPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				var pageCount = $formObject[formName].editList.pageCount;
				pageIndex++;
				if(pageIndex>pageCount){
					pageIndex = pageCount ;
				}
				$itfreer_form_core.setPageIndexAndQuery(formName, pageIndex, addResult);
			},
			
			//首页
			firstPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.setPageIndexAndQuery(formName, 1, addResult);
			},
			
			//尾页
			lastPage : function(formName, addResult){
				formName = formName ? formName : 'fd';
				var pageCount = $formObject[formName].editList.pageCount;
				$itfreer_form_core.setPageIndexAndQuery(formName, pageCount, addResult);
			},

			// 设置当前编辑记录 
			setEditRow : function(formName, row, childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				if($formObject[formName].hasOwnProperty("childTables")){
					childTables = childTables ? childTables : $formObject[formName].childTables;
				}
				if($formObject[formName].hasOwnProperty("childGridPara")){
					childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				}
				if($formObject[formName].hasOwnProperty("tagetTableNames")){
					tagetTableNames = tagetTableNames ? tagetTableNames : $formObject[formName].tagetTableNames;
				}
				if($formObject[formName].hasOwnProperty("childOrders")){
					childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				}
				
				if(childGridPara){
					$itfreer_form_core.clearChildGridSelect(childGridPara);
				}
				
				if(row != null && !row[$formObject.isNew]){
					$formObject[formName].curOldRow = row;
					var copyRow = jQuery.extend(true, {}, row);
					
					// 处理直接子表
					if(childTables){
						$itfreer_form_core.loadRowChildValue(formName, copyRow, childTables, childOrders);
					}
					
					// 处理中间表第一种情况
					if(childTables && tagetTableNames){
						$itfreer_form_core.loadRowChildValueByTagetTable(formName, copyRow, childTables, childOrders, tagetTableNames);
					}
					
					// 处理中间表第二种情况
					if(childGridPara){
						$itfreer_form_core.loadRowChildValueByGrid(formName, copyRow, childGridPara);
					}
					
					$formObject[formName].editRow = copyRow;
				}else{
					if($formObject[formName].hasOwnProperty("defaultObject")){
						if(row!=null){
							row = jQuery.extend(true, row, $formObject[formName].defaultObject);
						}else{
							row = jQuery.extend(true, {}, $formObject[formName].defaultObject);
						}
					}else{
						if(row==null){
							row = {};
						}
					}
					row[$formObject.isNew]=true;
					$formObject[formName].editRow = row;
				}
				
				// 有工作流，处理流程配置信息
				if($formObject[formName].bmpKey){
					$itfreer_form_core.loadBpmTaskFormConfig(formName, row);
					$itfreer_form_core.setBpmTaskConfig(formName, row);
				}
			},
			
			// 为当前记录加载子表数据 row : 数据行， childTables : 子表名称 , 如 "table1,table2" , 
			//	childOrders 子表排序，如：I_ORDER:1:ORDERFIELD2:0,I_ORDER:0，用，分开顺序和子表的顺序一样
			loadRowChildValue : function(formName, row, childTables, childOrders){
				formName = formName ? formName : 'fd';
				childTables = childTables ? childTables : $formObject[formName].childTables;
				childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				
				if(row==null || childTables==null){
					return;
				}
				
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						return;
					}
				}
				
				$itfreerHttp.getChildDataEx($formObject[formName].tableName, row, childTables, childOrders,
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 填充中间表子表数据，并根据中间表与关联的另外一张主表将外键关系，将另外一张主表的信息一起填充给中间子表记录
			// 如，用户表，用户角色表，角色表。当获取用户角色表时，可将角色表的信息一起查询出来，并给中间表子间填充
			// 如果另外一张主表中的字段在中间表中存在，则另外一张主表的字段改为字段名+"_OO"
			// row : 数据行， 
			// childTables : 中间表子表名称 , 如 "table1,table2" , 
			// childOrders : 子表排序，如：I_ORDER:1:ORDERFIELD2:0,I_ORDER:0，用，分开顺序和子表的顺序一样
			// tagetTableNames : 中间表关联表对象，如：tagetTableName:childField:tagetField:childField1:tagetField1,tagetTableName:childField:tagetField:childField1:tagetField1
			loadRowChildValueByTagetTable : function(formName, row, childTables, childOrders, tagetTableNames){
				formName = formName ? formName : 'fd';
				childTables = childTables ? childTables : $formObject[formName].childTables;
				childOrders = childOrders ? childOrders : $formObject[formName].childOrders;
				tagetTableNames = tagetTableNames ? tagetTableNames : $formObject[formName].tagetTableNames;
				
				if(row==null || childTables==null){
					return;
				}
				
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						return;
					}
				}
				
				$itfreerHttp.getChildDataEx2($formObject[formName].tableName, row, 
						childTables, childOrders, tagetTableNames, 
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 加载中间表数据，并根据子表数据，实现对子表TreeGrid控件的选择(如：在用户中处理用户选择角色的情况)
			// row : 数据行， childTables : 子表名称 , 如'gridName,childTableName,gridKey,tableKey:gridName,childTableName,gridKey,tableKey'
			loadRowChildValueByGrid : function(formName, row, childGridPara){
				formName = formName ? formName : 'fd';
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				var childTables = "";
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var childTableName = childItem[1];
				     		childTables += childTableName + ",";
				     	}
				    });
					childTables = childTables.substring(0, childTables.length-1);
				}
				$itfreer_form_core.clearChildGridSelect(childGridPara);
				
				if(row==null || childTables==null){
					$itfreer_form_core.updateChildGridSelect(childGridPara, row);
					return;
				}
				if(row.hasOwnProperty('childValues')){
					var childs = childTables.split(',');
					var needLoad = false;
					for(var i=0;i<childs.length;i++){
						if(!row.childValues.hasOwnProperty(childs[i])){
							needLoad = true;
							break;
						}
					}
					if(!needLoad){
						$itfreer_form_core.updateChildGridSelect(childGridPara, row);
						return;
					}
				}
				
				$itfreerHttp.getChildData($formObject[formName].tableName, row, childTables,
					function(data){
						$rootScope.$apply(function() {
							row.childValues = row.childValues ? row.childValues : {};
							if(data){
								data.forEach(function(e){
									for(attribute in e){ 
										row.childValues[attribute]=e[attribute];
									} 
								});
							}
							$itfreer_form_core.updateChildGridSelect(childGridPara, row);
							jQuery.extend(true, $formObject[formName].curOldRow, row);
						});
					}, 
					function(ex){
					}
				);
			},
			
			// 更新子Grid控件子表的选择
			updateChildGridSelect : function(childGridPara, row){
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		var childTableName = childItem[1];
				     		var gridKey = childItem[2];
				     		var tableKey = childItem[3];
				     		
				     		var tableData = row.childValues[childTableName];
				     		$itfreer_form_core.setChildSelect(gridName, tableData, gridKey, tableKey);
				     	}
				    });
				}
			},
			
			// 清除子Grid控件子表的选择
			clearChildGridSelect : function(childGridPara){
				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		$itfreer_form_core.clearGridSelect(gridName);
				     	}
				    });
				}
			},
			
			// 获取Grid选择的记录集
			getGridSelect : function(gridName, gridKey, tableKey){
				var treeGridControl = $('#'+gridName);
				var dataList = [];
			    $("input:checked").each(function(){
			        var id = $(this).attr("id");
			        if(id && id.indexOf(gridName+'_')>-1){
			        	id = id.replace(gridName+'_','');
			        	var sData = treeGridControl.treegrid('find', id);
			        	if(gridKey!=null && tableKey!=null){
			        		var tData = {};
			        		tData[tableKey] = sData[gridKey];
			        		dataList.push(tData);
			        	}else{
			        		dataList.push(sData);
			        	}
			        }
			    });
			    return dataList;
			},
			
			// 设置子Grid控件子表的选择
			setChildSelect : function(gridName, tableData, gridKey, tableKey){
				$("input:checked").each(function(){
			        var id = $(this).attr("id");
			        if(id && id.indexOf(gridName+'_')>-1){
			        	$(this).attr("checked",false);
			        }
			    });
				
				if(gridKey!=null && tableKey!=null
						&& tableData!=null && tableData.length>0){
					var treeGridControl = $('#'+gridName);
					$("input:checkbox[name='"+gridName+"']").each(function(){
				        var id = $(this).attr("id");
				        var gid = id.replace(gridName+'_','');
			        	var gData = treeGridControl.treegrid('find', gid);
			        	var gValue = gData[gridKey];
			        	tableData.forEach(function(e){
							var tValue = e[tableKey];
							if(gValue == tValue){
								$("#"+id).attr("checked",true);
								return;
							}
						});
				    });
				}
			},
			
			// 清除子Grid控件的选择
			clearGridSelect : function(gridName){
				$("input:checked").each(function(){
			        var id = $(this).attr("id");
			        id = id ? id : '';
			        if(id.indexOf(gridName+'_')>-1){
			        	$(this).attr("checked",false);
			        }
			    });
			},
			
			// 删除实体
			delEntity : function(formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", "确定删除此记录?", function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						var rowMap = {};
						rowMap[$formObject[formName].keyField] = row[$formObject[formName].keyField];
						$itfreerHttp.deleteByKey($formObject[formName].tableName, rowMap,
							function(data){
								$rootScope.$apply(function() {
									$formObject[formName].editList.list.remove(row);
									$formObject[formName].editList.rowsCount -= 1;
									$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
								});
							}, 
							function(xhr){
								if(xhr.hasOwnProperty('responseText') 
										&& xhr.responseText!=null
										&& xhr.responseText!=''){
									if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
										$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
									}else{
										$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
									}
								}else{
									$.messager.alert('系统提示', '删除失败！原因：请求超时！');
								}
							}
						);
					}
				});
			},
			
			// 批量删除实体
			delEntitys : function(formName){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", "确定删除选择记录?", function(r){
					if(r){
						var rows = $formObject[formName].editList.list;
						if(rows==null){
							return;
						}
						
						if($formObject[formName].bmpKey){
							// 不可删除记录
							var noDelRows = [];
							rows.forEach(function(e){  
								if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
									if(e["TASK_CANDEL"]!="1"){
										noDelRows.push(e);
									}
								}
							});
							
							if(noDelRows.length>0){
								$.messager.confirm("操作确认", "选择的记录中有部分记录不能被删除。是否自动取消不可删除记录的选择?", function(r){
									if(r){
										$rootScope.$apply(function(){
											noDelRows.forEach(function(e){  
												e[$formObject.selectedField] = false;
											});
											$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
										});
									}
								});
								return;
							}
						}
						
						var keys = $formObject[formName].keyField+":in";
						var values = "";
						var dRows = [];
						rows.forEach(function(e){  
							if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
								if (typeof (e[$formObject[formName].keyField]) == 'string'){
									values += "'"+e[$formObject[formName].keyField] + "',";
								}else{
									values += e[$formObject[formName].keyField] + ",";
								}
								dRows.push(e);
							}
						});
						if(values!=""){
							values = values.substr(0, values.length-1);
							var rowMap = {};
							rowMap[keys] = values;
							if($formObject[formName].bmpKey){
								$itfreerHttp.deleteByKeyInBpm($formObject[formName].tableName, rowMap, $formObject[formName].bmpKey,
										function(data){
											if(dRows.length == $formObject[formName].editList.pageSize){
												$itfreer_form_core.innerLoadData(formName, true, false);
											}else{
												$rootScope.$apply(function() {
													dRows.forEach(function(e){  
														$formObject[formName].editList.list.remove(e);
													});
													$formObject[formName].editList.rowsCount -= dRows.length;
												});
											}
										}, 
										function(xhr){
											if(xhr.hasOwnProperty('responseText') 
													&& xhr.responseText!=null
													&& xhr.responseText!=''){
												if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
													$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
												}else{
													$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
												}
											}else{
												$.messager.alert('系统提示', '删除失败！原因：请求超时！');
											}
										}
									);
							}else{
								$itfreerHttp.deleteByKey($formObject[formName].tableName, rowMap,
										function(data){
											if(dRows.length == $formObject[formName].editList.pageSize){
												$itfreer_form_core.innerLoadData(formName, true, false);
											}else{
												$rootScope.$apply(function() {
													dRows.forEach(function(e){  
														$formObject[formName].editList.list.remove(e);
													});
													$formObject[formName].editList.rowsCount -= dRows.length;
												});
											}
										}, 
										function(xhr){
											if(xhr.hasOwnProperty('responseText') 
													&& xhr.responseText!=null
													&& xhr.responseText!=''){
												if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
													$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
												}else{
													$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
												}
											}else{
												$.messager.alert('系统提示', '删除失败！原因：请求超时！');
											}
										}
									);
							}
						}else{
							
						}
						$itfreer_form_core.setSelectedRows($formObject[formName].editList.list);
					}
				});
			},
			
			// 逻辑添加子表的空记录，但不提交到数据库中 childTable子表名称，keyField 子表主键
			addChildNewRow : function(formName, childTable, keyField){
				formName = formName ? formName : 'fd';
				if(!$formObject[formName].editRow.hasOwnProperty('childValues')){
					$formObject[formName].editRow.childValues = {};
				}
				if(!$formObject[formName].editRow.childValues[childTable]){
					$formObject[formName].editRow.childValues[childTable] = [];
				}
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj[keyField] = guid;
				obj[$formObject.isNew] = true;
				$formObject[formName].editRow.childValues[childTable].push(obj);
			},

			// 逻辑添加空记录，但不提交到数据库中 list数据列表，keyField 子表主键
			addNewRow : function(list, keyField){
				if(!list){
					list = [];
				}
				var obj = {};
				var guid = $itfreer_core.getGUID();
				obj[keyField] = guid;
				obj[$formObject.isNew] = true;
				list.push(obj);
			},
			
			// 设置子表编辑对象
			setChildEditRow : function(formName, row, keyField){
				formName = formName ? formName : 'fd';
				if(row!=null){
					var copyRow = jQuery.extend(true, {}, row);
					$formObject[formName].cOldRow = row;
					$formObject[formName].cEditRow = copyRow;
				}else{
					var guid = $itfreer_core.getGUID();
					row = {};
					row[keyField] = guid;
					row[$formObject.isNew] = true;
					$formObject[formName].cOldRow = null;
					$formObject[formName].cEditRow = row;
				}
			},
			
			// 逻辑批量删除，不提交到数据库
			delSelectedEntitys : function(rowList){
				if(rowList==null){
					return;
				}
				var dRows = [];
				rowList.forEach(function(e){  
					if(e[$formObject.selectedField]!=null && e[$formObject.selectedField]==true){
						dRows.push(e);
					}
				});
				dRows.forEach(function(e){  
					rowList.remove(e);
				});
				$itfreer_form_core.setSelectedRows(rowList);
			},
			
			// 逻辑删除数据
			delEntityInList : function(rowList, row){
				rowList.remove(row);
				$itfreer_form_core.setSelectedRows(rowList);
			},
			
			// 逻辑保存子表记录，不保存到数据库
			saveChildRow : function(formName, childTableName, row, uniqueKey){
				formName = formName ? formName : 'fd';
				if($formObject[formName].cOldRow!=null){
					jQuery.extend(true, $formObject[formName].cOldRow, row);
				} else {
					if(!$formObject[formName].editRow.hasOwnProperty('childValues')){
						$formObject[formName].editRow.childValues = {};
					}
					if (!$formObject[formName].editRow.childValues[childTableName]) {
						$formObject[formName].editRow.childValues[childTableName] = [];
					};
					//按唯一条件删除子表重复记录
					if (uniqueKey) {
						for (var i = 0; i < $formObject[formName].editRow.childValues[childTableName].length; i++) {
							var item = $formObject[formName].editRow.childValues[childTableName][i];
							if (item[uniqueKey] && item[uniqueKey] == row[uniqueKey]) {
								$formObject[formName].editRow.childValues[childTableName].remove(item);
							};
						};
					};
					$formObject[formName].editRow.childValues[childTableName].push(row);
				}
			},

			// 初始化表单属性并加载数据
			initAndLoadGridData : function(formName, tableName, keyField, randomFields, 
					orderObject, formValue, queryValue, bmpKey, treeGirdName, 
					idField, pIDField, treeJBField, treeIsChildField, treeLoadJBs,
					childTables, childGridPara, tagetTableNames, childOrders){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.initTreePara(formName, tableName, keyField, randomFields, orderObject, 
						formValue, queryValue, bmpKey, treeGirdName, idField, pIDField, 
						treeJBField, treeIsChildField, treeLoadJBs,
						childTables, childGridPara, tagetTableNames, childOrders);
				$itfreer_form_core.loadTreeData(formName);
				if(bmpKey){
					$itfreer_form_core.loadBpmFormConfig(formName);
				}
			},
			
			// 内部树重新查询
			loadTreeData:function(formName){
				formName = formName ? formName : 'fd';
				var queryObject = jQuery.extend(true, $formObject[formName].queryObject, $formObject[formName].queryValue);
				$itfreerHttp.getTreeData($formObject[formName].tableName, queryObject, 
						$formObject[formName].orderObject, '', $formObject[formName].treeLoadJBs,'', 
						$formObject[formName].editList.pageSize, $formObject[formName].editList.pageIndex, false,
					function(treedata) {
						treedata = treedata ? treedata : [];
						$rootScope.$apply(function() {
							var treeGridControl = $('#'+$formObject[formName].treeGirdName);
							treeGridControl.treegrid('loadData', treedata);
						});
					}, function(ex) { }
				);
			},
			
			// 设置查询条件并查询
			setTreeQueryObjectAndQuery:function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].queryObject.hasOwnProperty(field)){
						delete $formObject[formName].queryObject[field];
					}
				}else{
					$formObject[formName].queryObject[field]=value;
				}
				$itfreer_form_core.loadTreeData(formName);
			},
			
			// 设置排序对象
			setTreeOrderObjectAndQuery:function(formName, field, value){
				formName = formName ? formName : 'fd';
				if(value==null || value == "null"){
					if($formObject[formName].orderObject.hasOwnProperty(field)){
						delete $formObject[formName].orderObject[field];
					}
				}else{
					$formObject[formName].orderObject[field]=value;
				}
				$itfreer_form_core.loadTreeData(formName);
			},
			
			// 设置分页索引并且重新查询数据
			setTreePageIndexAndQuery:function(formName, pageIndex){
				formName = formName ? formName : 'fd';
				$formObject[formName].editList.pageIndex = pageIndex;
				$itfreer_form_core.loadTreeData(formName);
			},
			
			//上一页
			preTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				pageIndex--;
				if(pageIndex<=0){
					pageIndex =1 ;
				}
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageIndex);
			},
			
			//下一页
			nextTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageIndex = $formObject[formName].editList.pageIndex;
				var pageCount = $formObject[formName].editList.pageCount;
				pageIndex++;
				if(pageIndex>pageCount){
					pageIndex = pageCount ;
				}
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageIndex);
			},
			
			//首页
			firstTreePage:function(formName){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.setTreePageIndexAndQuery(formName, 1);
			},
			
			//尾页
			lastTreePage:function(formName){
				formName = formName ? formName : 'fd';
				var pageCount = $formObject[formName].editList.pageCount;
				$itfreer_form_core.setTreePageIndexAndQuery(formName, pageCount);
			},

			// 添加树型数据的下级编辑记录
			addTreeNextEditRow:function(formName){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				var selectedNode = treeGridControl.treegrid('getSelected');
				if(selectedNode==null){
					$.messager.alert('系统提示', '请选择一个父节点！');
					return;
				}
				
				var row = null;
				if($formObject[formName].hasOwnProperty("defaultObject")){
					row = jQuery.extend(true, {}, $formObject[formName].defaultObject);
				}else{
					row = {};
				}
				row[$formObject.isNew]=true;
				row[$formObject[formName].pIDField] = selectedNode[$formObject[formName].idField];
				$formObject[formName].editRow = row;
				
				// 有工作流，处理流程配置信息
				if($formObject[formName].bmpKey){
					$itfreer_form_core.loadBpmTaskFormConfig(formName, row);
					$itfreer_form_core.setBpmTaskConfig(formName, row);
				}
			},
			
			// 编辑当前选择的树节点
			editTreeSelectedRow:function(formName, childTables){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				var row = treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个节点！');
					return;
				}
				$itfreer_form_core.setEditRow(formName, row, childTables, null, null, null);
			},
			
			// 删除当前选择的树节点
			delTreeSelectedRows:function(formName, tableName, row){
				formName = formName ? formName : 'fd';
				var treeGridControl = $('#'+$formObject[formName].treeGirdName);
				row = row ? row : treeGridControl.treegrid('getSelected');
				if(row==null){
					$.messager.alert('系统提示', '请选择一个节点！');
					return;
				}
				
				$.messager.confirm("操作确认", "确定删除此记录?", function(r){
					if(r){
						tableName = tableName ? tableName : $formObject[formName].tableName;
						
						var rowMap = {};
						rowMap[$formObject[formName].keyField] = row[$formObject[formName].keyField];
						$itfreerHttp.deleteByKey(tableName, rowMap,
							function(data){
								var pid = row[$formObject[formName].idField];
								// 看有没有上级
								var parentNode = treeGridControl.treegrid('getParent',pid);
								if(parentNode!=null){
									var id = parentNode[$formObject[formName].idField];
									var nodes = treeGridControl.treegrid('getChildren', id);
									if( (nodes==null || nodes.length <=1) && parentNode[$formObject[formName].treeIsChildField] == "0" ){
										parentNode[$formObject[formName].treeIsChildField] = "1";
										$itfreerHttp.save(tableName, parentNode,
											function(data){
												treeGridControl.treegrid('refresh',id); 
											}, 
											function(ex){ } );
									}
								}
								treeGridControl.treegrid('remove',pid);
								//alert('删除成功！');
							}, 
							function(xhr){
								if(xhr.hasOwnProperty('responseText') 
										&& xhr.responseText!=null
										&& xhr.responseText!=''){
									if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
										$.messager.alert('系统提示', '删除失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
									}else{
										$.messager.alert('系统提示', '删除失败！原因：'+xhr.responseText);
									}
								}else{
									$.messager.alert('系统提示', '删除失败！原因：请求超时！');
								}
							}
						);
					}
				});
			},

			// 保存实体
			save : function(formName, tableName, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction){
				formName = formName ? formName : 'fd';
				if($formObject.isOptioning){
					$.messager.alert("系统提示","系统处理中，请稍等！");
					return;
				}
				$formObject.isOptioning = true;

				childGridPara = childGridPara ? childGridPara : $formObject[formName].childGridPara;
				tableName = tableName ? tableName : $formObject[formName].tableName;
				row = row ? row : $formObject[formName].editRow;
				
				// 处理Grid选择子表，其它的不需要处理，因为子表数据就在数据中
				$formObject[formName].editRow.childValues = $formObject[formName].editRow.childValues ? $formObject[formName].editRow.childValues : {};
				// 更新子表数据
				if(childGridPara!=null){
					var childs = childGridPara.split(":");
					childs.forEach(function(item){
				     	var childItem = item.split(",");
				     	if(childItem.length==4){
				     		var gridName = childItem[0];
				     		var childTableName = childItem[1];
				     		var gridKey = childItem[2];
				     		var tableKey = childItem[3];
				     		
				     		if($formObject[formName].editRow.childValues.hasOwnProperty(childTableName) && $("#gridName").length > 0){
				     			delete $formObject[formName].editRow.childValues[childTableName];
							}
				     		if($("#"+gridName).length > 0){
				     			var childData = $itfreer_form_core.getGridSelect(gridName, gridKey, tableKey);
					     		$formObject[formName].editRow.childValues[childTableName] = childData;
				     		}
				     	}
				    });
				}
				
				// 处理自动增值键
				if(row[$formObject[formName].keyField]==null || row[$formObject[formName].keyField]==""){
					var guid = $itfreer_core.getGUID();
					row[$formObject[formName].keyField] = guid;
				}
				
				// 处理随机赋值字段
				if($formObject[formName].randomFields){
					for (var i = 0; i < $formObject[formName].randomFields.length; i++) {
						var randomField = $formObject[formName].randomFields[i];
						if (row[randomField]==null || row[randomField]=="") {
							var randomValue = $itfreer_core.getGUID();
							row[randomField] = randomValue;
						};
					};
				}
				
				// 处理工作流定义ID
				if($formObject[formName].bmpKey != null && $formObject[formName].bmpKey != ""){
					row["ACTIVITIKEY"] = $formObject[formName].bmpKey;
				} else {
					row["ACTIVITIKEY"] = "";
				}
				
				// 是否工作流保存操作
				if(byBpmSave){
					row["ACTIVITISAVE"] = "1";
				} else {
					row["ACTIVITISAVE"] = "0";
				}
				
				// 处理工作流默认对象
				if(bmpObject != null){
					// 复制对象中的值
					row = $.extend(row, bmpObject); 
				}
				
				// 处理下一节点审批人信息
				if($formObject.nextAssignees.length>0){
					var taskString = "";
					var isReturn = false;
					$formObject.nextAssignees.forEach(function(taskItem){
						// 任务key,user1,username:任务key,user1,username
				     	var taskid = taskItem.taskid;
				     	var taskname = taskItem.taskname;
				     	taskString += taskid + ",";
				     	var findUser = false;
				     	taskItem.data.forEach(function(dateItem){
				     		if(dateItem.checked == "1"){
				     			var userid = dateItem.id;
				     			var username = dateItem.text;
				     			
				     			taskString += userid + ",";
				     			taskString += username + ",";
				     			findUser = true;
				     		}
				     	});
				     	if(findUser){
				     		taskString = taskString.substring(0, taskString.length-1);
				     		taskString += ":";
				     	}else{
				     		$.messager.alert('系统提示', "【"+taskname+"】节点未指定审批用户！");
				     		isReturn = true;
				     		return;
				     	}
				    });
					if(isReturn){
						return;
					}
					taskString = taskString.substring(0, taskString.length-1);
					row["TASKUSER"] = taskString;
				}
				
				if($formObject.nextTasks.length>0){
					var tjTasks = "";
					for(var i=0;i<$formObject.nextTasks.length;i++){
						if($formObject.nextTasks[i].checked == "1"){
							tjTasks += $formObject.nextTasks[i].id + ",";
						}
					}
					if(tjTasks==""){
						$.messager.alert('系统提示', "至少得选择一个提交节点！");
			     		return;
					}
					tjTasks = tjTasks.substring(0, tjTasks.length-1);
					row["TJTASKS"] = tjTasks;
				}
				
				// 处理交办信息
				if($formObject.bpmJb.userid!="" && $formObject.bpmJb.username!=""){
					row["JBUSER"] = $formObject.bpmJb.userid + "," + $formObject.bpmJb.username;
				}
				
				// 处理treeGrid的添加顶级和添加下级事项
				var node = null;
				var treeGridControl = null;
				if($formObject[formName].treeGirdName 
						&& $formObject[formName].treeGirdName!=""){
					treeGridControl = $('#'+$formObject[formName].treeGirdName);
					node = treeGridControl.treegrid('getSelected');
					// 添加顶级项
					if(row[$formObject[formName].pIDField] == null){
						row[$formObject[formName].treeJBField] = 1;
						row[$formObject[formName].treeIsChildField] = "1";
					} else {
						// 添加下级项
						if(row[$formObject[formName].idField] != node[$formObject[formName].idField]){
							var level = treeGridControl.treegrid('getLevel', node[$formObject[formName].idField]);
							row[$formObject[formName].treeJBField] = level + 1;
							row[$formObject[formName].treeIsChildField] = "1";
						}
					}
				}
				$itfreerHttp.save(tableName, row,
						function(data){
					// 表单保存的拦截未通过
					if(data.unpass && data.unpass.length>0){
						if(failFunction!=null){
							failFunction(data);
						}
					} else {
						$rootScope.$apply(function() {
							
							$itfreer_form_core.doChilds(data);

							if(row.hasOwnProperty("childValues")){
								delete row["childValues"];
							}
							jQuery.extend(true, row, data);
							
							// 处理新对象无刷插入
							if(row[$formObject.isNew]==null || row[$formObject.isNew]==true){
								// 新对象，插入
								row[$formObject.isNew] = false;
								if(!$formObject[formName].hasOwnProperty("editList")){
									$formObject[formName].editList = {};
								}
								if(!$formObject[formName].editList.hasOwnProperty("list")){
									$formObject[formName].editList.list = [];
								}
								$formObject[formName].editList.list.unshift(row);
								$formObject[formName].editList.rowsCount += 1;
								
								// 如果treeGrid不为空，说明是树操作
								if($formObject[formName].treeGirdName 
										&& $formObject[formName].treeGirdName != ""){
									var datas = [];
									datas.push(row);
									var treeGridControlEx = $('#'+$formObject[formName].treeGirdName);
									// 添加顶级项
									if(row[$formObject[formName].pIDField] == null){
										treeGridControlEx.treegrid('append',{
											parent: null,  data: datas });
									} else {
										// 添加下级项
										treeGridControlEx.treegrid('append',{
											parent: node[$formObject[formName].idField], data: datas });
										// 处理上级的数据
										if(node[$formObject[formName].treeIsChildField] == "1"){
											node[$formObject[formName].treeIsChildField] = "0";
											$itfreerHttp.save(tableName, node,
													function(data){
												treeGridControlEx.treegrid('refresh',node[$formObject[formName].idField]); 
											}, 
											function(ex){ } );
										}
									}
								}
							}else{
								// 更新对象
								if($formObject[formName].curOldRow){
									if($formObject[formName].curOldRow.hasOwnProperty("childValues")){
										delete $formObject[formName].curOldRow["childValues"];
									}
									jQuery.extend(true, $formObject[formName].curOldRow, data);
								}
								if($formObject[formName].treeGirdName 
										&& $formObject[formName].treeGirdName != ""){
									// 更新树对象，不处理子节点与级别
									var treeGridControl = $('#'+$formObject[formName].treeGirdName);
									treeGridControl.treegrid('refresh', data[$formObject[formName].idField]);
								}
							}

							// 有工作流，处理流程配置信息
							if($formObject[formName].bmpKey){
								$itfreer_form_core.loadBpmTaskFormConfig(formName, data);
								$itfreer_form_core.setBpmTaskConfig(formName, data);
							}
						
						});
						
						if(successFunction!=null){
							successFunction();
						}
						//alert('保存成功！');
					}
					$formObject.isOptioning = false;
				}, function(xhr,textStatus){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '保存失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '保存失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '保存失败！原因：请求超时！');
						}
						
						if(failFunction!=null){
							failFunction();
						}
						$formObject.isOptioning = false;
					}
				);
			},
			
			// 将数据的子表数据处理为旧数据 $formObject.isNew = false;
			doChilds : function(row){
				if(!row.hasOwnProperty('childValues')){
					return;
				}
				for(attribute in row.childValues){ 
				     var datas = row.childValues[attribute];
				     datas.forEach(function(ed){
				     	ed[$formObject.isNew] = false;
				     });
				     break;
				}
			},
			
			// 保存实体集
			saveEntitys : function(rows, formName){
				formName = formName ? formName : 'fd';
				$itfreerHttp.saveList($formObject[formName].tableName, rows,
					function(data){
						$.messager.alert('系统提示', '保存成功！');
					}, 
					function(xhr,textStatus){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '保存失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '保存失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '保存失败！原因：请求超时！');
						}
					}
				);
			},

			// 设置全选 checkName:checked控件名称，rowList:要选择的数据列表对象,field:选择的字段，默认为selectedField
			setAllSelected : function(checkName, rowList, field, trueValue, falseValue){
				field = field ? field : $formObject.selectedField;
				var checked = $("#"+checkName).attr("checked") == "checked";
				var checkedValue = null;
				if(checked){
					checkedValue = trueValue ? trueValue : checked;
				}else{
					checkedValue = falseValue ? falseValue : checked;
				}
				if(rowList.hasOwnProperty("list")){
					rowList.checkedRow = null;
					rowList.checkedRows = [];
					rowList.list.forEach(function(e){  
					    e[field] = checkedValue;
					    if(checked){
					    	rowList.checkedRows.push(e);
					    }
					});
					if(rowList.checkedRows.length==1){
						rowList.checkedRow = rowList.checkedRows[0];
					}
				} else {
					rowList.forEach(function(e){
					    e[field] = checkedValue;
					});
				}
			},
			
			// 根据rowList中的数据选择情况，重新处理rowList.checkedRows和rowList.checkedRow值。
			setSelectedRows : function(rowList){
				if(rowList.hasOwnProperty("list")){
					rowList.checkedRow = null;
					rowList.checkedRows = [];
					rowList.list.forEach(function(e){  
					    var checked = e[$formObject.selectedField];
					    if(checked){
					    	rowList.checkedRows.push(e);
					    }
					});
					if(rowList.checkedRows.length==1){
						rowList.checkedRow = rowList.checkedRows[0];
					}
				}
			},
			
			// 选择或取消选择，rowList：数据列表,row:需选择数据,onlySelect:是否只选择指定数据
			selectRow : function(rowList, row, onlySelect){
				var checked = !row.hasOwnProperty($formObject.selectedField) || !row[$formObject.selectedField];
				if(rowList.hasOwnProperty("list")){
					if(onlySelect){
						rowList.list.forEach(function(e){
							if(row!=e){
								e[$formObject.selectedField]=false;
							}
						});
						rowList.checkedRows = [];
						if(checked){
							rowList.checkedRow = row;
							rowList.checkedRows.push(row);
						}else{
							rowList.checkedRow = null;
						}
					}else{
						rowList.checkedRows = [];
						rowList.list.forEach(function(e){
							if(row!=e 
									&& e.hasOwnProperty($formObject.selectedField)
									&& e[$formObject.selectedField]){
								rowList.checkedRows.push(e);
							}
						});
						if(checked){
							rowList.checkedRows.push(row);
						}
						if(rowList.checkedRows.length==1){
							rowList.checkedRow = rowList.checkedRows[0];
						}else{
							rowList.checkedRow = null;
						}
					}
				}else{
					if(onlySelect){
						rowList.forEach(function(e){
							if(row!=e){
								e[$formObject.selectedField]=false;
							}
						});
					}
				}
			},

			// word导出
			exportDoc : function(dataMap, flt, fileName) {
				$itfreerHttp.exportDoc(dataMap, flt, fileName,
					function(data){
						var url = getBasePath() + "/" + data;
						window.open(url);
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '导出失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '导出失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '导出失败！原因：请求超时！');
						}
					}
				);
			},

			// 工作流中的撤销，交办等保存工作
			saveByBpm : function(msg, formName, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						$formObject.nextAssignees = [];
						$formObject.nextTasks = [];
						$itfreer_form_core.save(formName, null, row, byBpmSave, bmpObject, childGridPara, successFunction, failFunction);
					}
				});
			},
			
			// 工作流定义的挂起与激活
			suspendOrActivateByBpm : function(msg, type, formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						if(row==null){
							return;
						}
						if(row["TASK_DEFINID"] == null
								|| row["TASK_DEFINID"] == ""){
							return;
						}
						var id = row["TASK_DEFINID"];
						$itfreerHttp.suspendOrActivateByBpm(id,type,
							function(data){
								$.messager.alert('系统提示', data.result);
							}, 
							function(xhr){
								 if(xhr.hasOwnProperty('responseText') 
								 		&& xhr.responseText!=null
								 		&& xhr.responseText!=''){
								 	$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
								 }
							}
						);
					}
				});
			},

			// 工作流实例的挂起与激活
			suspendOrActivateByInst : function(msg, type, formName, row){
				formName = formName ? formName : 'fd';
				$.messager.confirm("操作确认", '确定'+msg+'吗?', function(r){
					if(r){
						row = row ? row : $formObject[formName].editRow;
						$formObject.historyRow = [];
						if(row==null){
							return;
						}
						if(row["TASK_PROID"] == null
								|| row["TASK_PROID"] == ""){
							return;
						}
						var id = row["TASK_PROID"];
						var bussId = row["GUID"];
						$itfreerHttp.suspendOrActivateByInst(id,type,bussId,
							function(data){
								
							}, 
							function(xhr){
								 if(xhr.hasOwnProperty('responseText') 
									 		&& xhr.responseText!=null
									 		&& xhr.responseText!=''){
									 	$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
								 }
							}
						);
					}
				});
			},

			// 流程第一次提交时，先做保存，再做提交，来解决第一次提交时不能提示用户确认第二个节点的审批用户信息
			saveByFirst : function(formName, row, bmpObject, childGridPara, 
				successFunction, failFunction){
				formName = formName ? formName : 'fd';
				if(!row){
					$.messager.alert('系统提示','表单值收集错误！');
					return;
				}

				if(!row.hasOwnProperty($formObject.isNew) 
					|| row[$formObject.isNew] == null
					|| row[$formObject.isNew] == true){
					$.messager.confirm("操作确认", '确定提交吗?', function(r){
						if(r){
							$formObject.nextAssignees = [];
							$formObject.nextTasks = [];
							// 先保存
							$itfreer_form_core.save(formName, null, row, false, 
								bmpObject, childGridPara, function(data){
								if(successFunction){
									successFunction();
								}
							}, failFunction);
						}
					});
				}else{
					if(successFunction){
						successFunction();
					}
				}
			},

			// 加载工作流的表单配置信息
			loadBpmFormConfig : function(formName){
				formName = formName ? formName : 'fd';
				if($formObject[formName].hasOwnProperty("bpmFormList")
						&& typeof($formObject[formName].bpmFormList) != "undefined"
						&& $formObject[formName].bpmFormList != null){
					return;
				}
				
				// 定义当前工作流的表单配置信息
				$formObject[formName].bpmFormList = null;
				$itfreerHttp.getBpmForms($formObject[formName].bmpKey,
					function(data){
						$formObject[formName].bpmFormList = data;
						
						// 数据加载后，如果需要处理流程对象
						if(typeof($formObject[formName].bpmFormList) != "undefined"
							&& $formObject[formName].bpmFormList != null
							&& typeof($formObject[formName].bpm) != "undefined"
							&& $formObject[formName].bpm != null
							&& $formObject[formName].bpm.hasOwnProperty("row")
							&& typeof($formObject[formName].bpm.row) != "undefined"
							&& $formObject[formName].bpm.row != null){
							$rootScope.$apply(function() {
								$itfreer_form_core.loadBpmTaskFormConfig(formName, $formObject[formName].bpm.row);
								$itfreer_form_core.setBpmTaskConfig(formName, $formObject[formName].bpm.row);
							});
						}
					}, 
					function(xhr){
						// if(xhr.hasOwnProperty('responseText') 
						// 		&& xhr.responseText!=null
						// 		&& xhr.responseText!=''){
						// 	if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
						// 		$.messager.alert('系统提示', '流程表单配置获取失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						// 	}else{
						// 		$.messager.alert('系统提示', '流程表单配置获取失败！原因：'+xhr.responseText);
						// 	}
						// }else{
						// 	$.messager.alert('系统提示', '流程表单配置获取失败！原因：请求超时！');
						// }
					}
				);
			},
			
			// 加载工作流当前节点的表单配置信息
			loadBpmTaskFormConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				$formObject[formName].bpm = {};
				
				if(typeof($formObject[formName].bpmFormList) == "undefined"
					|| $formObject[formName].bpmFormList == null){
					$formObject[formName].bpm.row = row;
					return;
				}
				
				var id = "";
				if(row != null
						&& row["TASK_TASKID"] != null
						&& row["TASK_TASKID"] != ""){
					id = row["TASK_TASKID"];
				} else {
					id = "U0";
				}
				
				// 当前任务的审批人信息
				var taskAssig = row["TASK_ASSIGNEES"];
				if(taskAssig==null || taskAssig==""){
					taskAssig = "";
				}
				// 任务：审批人信息
				var tasks = taskAssig.split(":");
				var userid = $formObject.user.userid;
				userid = userid ? userid : "-1";
				
				var ids = id.split(",");
				var allObject = {};
				for(var i=0;i<ids.length;i++){
					id = ids[i];
					if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
						continue;
					}
					
					// 查看当前人是不是有可编辑权限
					var canAu = true;
			    	if(userid != "-1" && tasks.length>0){
			    		for(var j=0; j<tasks.length; j++){
			    			var users = tasks[j].split(",");
			    			var taskId = users[0];
			    			if(id == taskId){
			    				var isau = tasks[j].indexOf(userid, 0);
				    			if(isau<0){
				    				canAu = false;
				    			}
				    			break;
			    			}
			            }
			    	}
					if(!canAu){
						continue;
					}
					var bpmObject = $formObject[formName].bpmFormList[id];
					for(obj in bpmObject){ 
						if(!allObject.hasOwnProperty(obj)){
							allObject[obj] = bpmObject[obj];
						}else{
							var objValue = allObject[obj] || bpmObject[obj];
							allObject[obj] = objValue;
						}
					}
				}
				$formObject[formName].bpm = allObject;
				$itfreer_form_core.loadBpmTaskTabConfig(formName, row);
			},
			
			// 加载工作流当前节点的Tab配置信息
			loadBpmTaskTabConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				if($formObject[formName].bpmFormList==null){
					return;
				}
				
				var id = "";
				if(row != null
						&& row["TASK_TASKID"] != null
						&& row["TASK_TASKID"] != ""){
					id = row["TASK_TASKID"];
				} else {
					id = "U0";
				}
				
				var ids = id.split(",");
				if(ids.length==1){
					var id = ids[0];
					if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
						return;
					}
					var bpmObject = $formObject[formName].bpmFormList[id];
					if(bpmObject.hasOwnProperty("_showTab")){
						var tabMsgs = bpmObject["_showTab"].split('.');
						if(tabMsgs.length==2){
							$itfreer_form_core.setTab(tabMsgs[0], tabMsgs[1]);
						}
					}
				}else{
					var taskAssig = row["TASK_ASSIGNEES"];
					if(taskAssig==null || taskAssig==""){
						taskAssig = "";
					}
					var tasks = taskAssig.split(":");
					if(tasks.length>1){
			    		for(var j=0; j<tasks.length; j++){
			    			var users = tasks[j].split(",");
			    			var id = users[0];
			    			if(!$formObject[formName].bpmFormList.hasOwnProperty(id)){
		    					continue;
		    				}
		    				var bpmObject = $formObject[formName].bpmFormList[id];
		    				if(bpmObject.hasOwnProperty("_showTab")){
		    					var tabMsgs = bpmObject["_showTab"].split('.');
		    					if(tabMsgs.length==2){
		    						$itfreer_form_core.setTab(tabMsgs[0], tabMsgs[1]);
		    					}
		    					return;
		    				}
			            }
			    	}
				}
			},
			
			// 加载工作流审批历史和流程图
			loadHistoryAndImage : function(formName, row, iboxName){
				formName = formName ? formName : 'fd';
				$itfreer_form_core.loadHistoryRow(formName, row);
				$itfreer_form_core.showBpmImage(formName, row, iboxName);
			},
			
			// 加载工作流审批历史
			loadHistoryRow : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				
				$formObject.historyRow = [];
				if(row==null){
					return;
				}
				if(row["TASK_PROID"] == null
						|| row["TASK_PROID"] == ""){
					return;
				}
				var id = row["TASK_PROID"];
				$itfreerHttp.getBpmHistory(id,
					function(data){
						$rootScope.$apply(function() {
							$formObject.historyRow = data;
						});
					}, 
					function(xhr){
						// if(xhr.hasOwnProperty('responseText') 
						// 		&& xhr.responseText!=null
						// 		&& xhr.responseText!=''){
						// 	if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
						// 		$.messager.alert('系统提示', '审批历史失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
						// 	}else{
						// 		$.messager.alert('系统提示', '审批历史失败！原因：'+xhr.responseText);
						// 	}
						// }else{
						// 	$.messager.alert('系统提示', '审批历史失败！原因：请求超时！');
						// }
					}
				);
			},
			
			// 显示流程图  row : 流程业务数据，iboxName : 弹窗名称
			showBpmImage : function(formName, row, iboxName){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				iboxName = iboxName ? iboxName : 'bpm';
				
				if(row==null){
					$.messager.alert('系统提示', '请选择需要查看的数据！');
					return;
				}
				if(row["TASK_PROID"] == null
						|| row["TASK_PROID"] == ""){
					$.messager.alert('系统提示', '请先发启流程！');
					return;
				}
				var id = row["TASK_PROID"];
				var loadSrc = getBasePath()+"/style/images/load.gif";
				$('#'+iboxName+'_img').attr("src", loadSrc);
				var guid = $itfreer_core.getGUID();
				var src=getBasePath()+"/workflow/exeimage.do?definitionId="+$formObject[formName].bmpKey+"&executionId="+id+"&guid="+guid;
				$('#'+iboxName+'_img').attr("src", src);
				$itfreer_form_core.openWindow(iboxName);
			},
			
			// 设置当前工作流的节点配置信息，主要是当前节点的审批人，下一节点信息
			setBpmTaskConfig : function(formName, row){
				formName = formName ? formName : 'fd';
				row = row ? row : $formObject[formName].editRow;
				// 设置下一接点
				$formObject.nextAssignees = [];
				var taskAssigness =  row["TASK_NEXTASSIGNEES"];
				if(taskAssigness==null || taskAssigness==""){
					$formObject.nextAssignees = [];
				} else {
					$formObject.nextAssignees = [];
					var taskes = taskAssigness.split(":");
					taskes.forEach(function(item){
						var taskItemString = item.split(",");
						var taskItem = {};
						taskItem.taskid = taskItemString[0];
						taskItem.taskname = taskItemString[1];
						var taskUsers = [];
						for(var i=2;i<taskItemString.length;i+=2){
							var dateItem = {};
							dateItem.id = taskItemString[i];
							dateItem.text = taskItemString[i+1];
							dateItem.checked = "1";
							taskUsers.push(dateItem);
						}
						taskItem.data = taskUsers;
						$formObject.nextAssignees.push(taskItem);
					});
				}
				// 设置提交节点
				$formObject.nextTasks = [];
				var taskAssig = row["TASK_ASSIGNEES"];
				if(taskAssig==null || taskAssig==""){
					taskAssig = "";
				}
				var tasks = taskAssig.split(":");
				
		    	if(tasks.length>1){
		    		var userid = $formObject.user.userid;
		    		userid = userid ? userid : "-1";
		    		
		    		for(var j=0; j<tasks.length; j++){
		    			var users = tasks[j].split(",");
		    			var taskObject = {};
		    			taskObject.id = users[0];
		    			taskObject.text = users[1];
		    			taskObject.checked = "1";
		    			
		    			if(userid=="-1"){
		    				$formObject.nextTasks.push(taskObject);
		    			}else{
		    				var isau = tasks[j].indexOf(userid, 0);
		        			if(isau>=0){
		        				$formObject.nextTasks.push(taskObject);
		        			}
		    			}
		            }
		    	}
			},
			
			// 判断当前用户是否可审批数据节点
			isAU : function(formName){
				formName = formName ? formName : 'fd';
				var assigneeUser = $formObject[formName].editRow["TASK_ASSIGNEES"];
				if(assigneeUser==null || assigneeUser==""){
					return true;
				}
				var userid = $formObject.user.userid;
				if(userid==null || userid==""){
					return false;
				}
				if(userid=="-1"){
					return true;
				}
				var isau = assigneeUser.indexOf(userid, 0);
				return isau>=0;
			},
			
			// 判断当前用户是否可主动已提交的流程
			isCh : function(formName){
				formName = formName ? formName : 'fd';
				var assigneeUser = $formObject[formName].editRow["TASK_PTASKUSER"];
				if(assigneeUser==null || assigneeUser==""){
					return false;
				}
				var userid = $formObject.user.userid;
				if(userid==null || userid==""){
					return false;
				}
				
				var historys = assigneeUser.split("&");
				var last = historys[historys.length-1];
				var lastMsg = last.split("~");
				var taskUserMsg = lastMsg[0];
				var taskUser = taskUserMsg.split(",");
				if(userid==taskUser[2]){
					return true;
				}else{
					return false;
				}
			},

			// 自动保存流程配置
			autoSaveTask : function(formName, pdId) {
				formName = formName ? formName : 'fd';
				$itfreerHttp.autoSaveTask(pdId,
					function(data){
						$rootScope.$apply(function() {
							var row = data;
							row[$formObject.isNew] = false;
							$itfreer_form_core.doChilds(row);
							$formObject[formName].editList.list.unshift(row);
						});
					}, 
					function(xhr){
						if(xhr.hasOwnProperty('responseText') 
								&& xhr.responseText!=null
								&& xhr.responseText!=''){
							if(xhr.responseText.indexOf('/fjkz/login/userLogin', 0) >= 0){
								$.messager.alert('系统提示', '创建失败！原因：会话已超时或当前帐号已在其它地方登录，请重新登录！');
							}else{
								$.messager.alert('系统提示', '创建失败！原因：'+xhr.responseText);
							}
						}else{
							$.messager.alert('系统提示', '创建失败！原因：请求超时！');
						}
					}
				);
			},

			// 加载表单，并打开表单
			// formUrl:表单地址，popName:弹窗名称，formName:表单名称, row:表单编辑的数据
			// <param name="defaultValueFun" type="Funciton" >表单默认值处理回调函数</param>
			openForm : function(formUrl, popName, formName, row, defaultValueFun){
				formName = formName ? formName : 'fd';
				if(defaultValueFun){
					row = defaultValueFun(row);
				}
				if(formUrl != $location.path()){
					$formObject.tempObject.openFormKey = "openForm";
					$formObject.tempObject.popName = popName;
					$formObject.tempObject.formName = formName;
					$formObject.tempObject.data = row;
					
					$location.path(formUrl);
					$location.replace();
				}else{
					$itfreer_form_core.setEditRow(formName, row);			
					$itfreer_form_core.openPop(popName);
				}
			},
			
			// formUrl:表单地址，popName:弹窗名称，formName:表单名称, row:表单编辑的数据
			openFormByKey : function(formUrl, popName, formName, tableName, key, defaultValueFun){
				formName = formName ? formName : 'fd';
				if(formUrl != $location.path()){
					$formObject.tempObject.openFormKey = "openFormByKey";
					$formObject.tempObject.popName = popName;
					$formObject.tempObject.formName = formName;
					$formObject.tempObject.tableName = tableName;
					$formObject.tempObject.formDataKey = key;
					$formObject.tempObject.defaultValueFun = defaultValueFun;
					
					$location.path(formUrl);
					$location.replace();
				}else{
					$itfreerHttp.getEntityByKey(tableName, key,
						function(data){
							$rootScope.$apply(function() {
								if(defaultValueFun){
									data = defaultValueFun(data);
								}
								$itfreer_form_core.setEditRow(formName, data);
							});
						}, 
						function(xhr){ }
					);
				}
			},

			// 销毁表单
			destroyForm : function(){
				// 删除当前的表单数据
				if($formObject.formNames.length>0){
					for(var i=0;i<$formObject.formNames.length;i++){
						var formName = $formObject.formNames[i];
						if($formObject.hasOwnProperty(formName)){
							delete $formObject[formName];
						}
					}
				}
				$formObject.formNames = [];
			},

			// easy ui
			destroyEasyui : function(){
				// 销毁easy ui对象
				if($formObject.windows.length>0){
					for(var i=0;i<$formObject.windows.length;i++){
						try{
							var pw = $formObject.windows[i];
							pw.window("destroy");
						}catch(e){}
					}
				}
				$formObject.windows = [];

				// 销毁easy ui对象
				if($formObject.combotrees.length>0){
					for(var i=0;i<$formObject.combotrees.length;i++){
						try{
							var pw = $formObject.combotrees[i];
							pw.combotree("destroy");
						}catch(e){}
					}
				}
				$formObject.combotrees = [];

				// 销毁easy ui对象
				if($formObject.comboboxs.length>0){
					for(var i=0;i<$formObject.comboboxs.length;i++){
						try{
							var pw = $formObject.comboboxs[i];
							pw.combobox("destroy");
						}catch(e){}
					}
				}
				$formObject.comboboxs = [];

				// 销毁easy ui对象
				if($formObject.treegrids.length>0){
					for(var i=0;i<$formObject.treegrids.length;i++){
						try{
							var pw = $formObject.treegrids[i];
							pw.treegrid("destroy");
						}catch(e){}
					}
				}
				$formObject.treegrids = [];

				// 销毁easy ui对象
				if($formObject.dateboxs.length>0){
					for(var i=0;i<$formObject.dateboxs.length;i++){
						try{
							var pw = $formObject.dateboxs[i];
							pw.datebox("destroy");
						}catch(e){}
					}
				}
				$formObject.dateboxs = [];
				// 销毁easy ui对象
				if($formObject.datetimeboxs.length>0){
					for(var i=0;i<$formObject.datetimeboxs.length;i++){
						try{
							var pw = $formObject.datetimeboxs[i];
							pw.datetimebox("destroy");
						}catch(e){}
					}
				}
				$formObject.datetimeboxs = [];
			}
		};
		for(f in $itfreer_form_core){
			$rootScope[f] = $itfreer_form_core[f];
		}
		$rootScope.formObject = $formObject;
		return $itfreer_form_core;
	});

	/**
	 * 表单第一个控制器
	 */
	itfreerformcoreModule.controller('misFirstRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core','$state','$wdp',
		function($scope,$itfreerHttp, $formObject, $itfreer_form_core,$state,$wdp){
			$(".zs-ibox .title i a").toggle(function(){
				$(this).removeClass("up").addClass("down").parent().parent().next().slideUp();
			},function(){
				$(this).removeClass("down").addClass("up").parent().parent().next().slideDown();	
			})
			var stateName = $state.current.name;
			//$("a[ui-sref='"+stateName+"']").addClass("selected");
			$formObject.isMIS = true;
			$itfreer_form_core.destroyForm();
			$itfreer_form_core.destroyEasyui();
			$scope.stateObj = $state.current;
		}
	]);

	/**
	 * 表单最后一个控制器
	 */
	itfreerformcoreModule.controller('misLastRouterCtrl', ['$scope', '$itfreerHttp', '$formObject', '$itfreer_form_core',
		function($stateParams,$scope, $itfreerHttp, $formObject, $itfreer_form_core){
			$formObject.isMIS = true;
			$scope.materialShow=getWaterType();
			if(!$formObject.tempObject || !$formObject.tempObject.openFormKey){
				return;
			}

			var openFormKey = $formObject.tempObject.openFormKey;
			if(openFormKey=="openForm"){
				$itfreer_form_core.setEditRow($formObject.tempObject.formName, $formObject.tempObject.data);
			} else if(openFormKey=="openFormByKey"){
				 $itfreerHttp.getEntityByKey($formObject.tempObject.tableName, $formObject.tempObject.formDataKey,
					function(data){
						$scope.$apply(function() {
							if($formObject.tempObject.defaultValueFun){
								data = $formObject.tempObject.defaultValueFun(data);
							}
							$itfreer_form_core.setEditRow($formObject.tempObject.formName, data);
						});
					}, 
					function(xhr){ }
				);
			}
			$formObject.tempObject.openFormKey = "";
		}
	]);

	/**
	 * combotree控件
	 */
	itfreerformcoreModule.directive('agCombotree', function($http, $itfreerHttp, $itfreer_core, $formObject, $rootScope) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			template : '<select ></select>',
			scope : {
				data : "=",
				textValue : "@",
				unitValue : "@",
				selectedRow : "@",
				onlySelectLeaf : "@",
				click:"&ngClick"
			},
			link : function(scope, element, attrs, ctrl) {
				var bindValue = null;
				var order = {};
				order[attrs.order] = 1;
				var queryObject = attrs.queryObject || '';
				var pId = attrs.pId || '';
				var domainName = attrs.domainName || '';
				var jbs = attrs.jbs || '';
				var delay = attrs.delay === "true" ? true :false;
				var isLoaded = false;
				var jbField = attrs.jbfield || '';
				var allLoadJB = attrs.allloadjb || -1;
				
				var onlySelectLeaf = attrs.onlyselectleaf == "true" ? true : false;
				var multiple = attrs.multiple === "true" ? true : false;
				var options = {
					data : scope.data,
					disabled:attrs.disabled == "true"?true:false,
					multiple : multiple
				};
				
				scope.uiclick = function(){
					if($scope.click()){
		    			$scope.click()();
		    		}
				}
				
				if (multiple == true) {
					options.onCheck = function (node,checked) {
						var values = element.combotree('getValues');
						if (values) {
							if (values.length < 2) {
								//如果多选值只有一个或者没有，将数组改为字符串
								values = values[0] || '';
							}
							//转换为字符串
							values = values.join();
						};
						safeApply(scope,function() {
							ctrl.$setViewValue(values);
						});
					};
				}else{
					options.onSelect = function(record) {
						safeApply(scope,function() {
							ctrl.$setViewValue(record.id);
							
							var binder = $itfreer_core.getBinder(scope, scope.textValue);
							if (binder != null) {
								var text = record ? record.text : "";
								binder.obj[binder.field] = text;
							}
							
							binder = $itfreer_core.getBinder(scope, scope.unitValue);
							if (binder != null) {
								if(record && record.attributes && record.attributes.S_UNIT){
									binder.obj[binder.field] = record.attributes.S_UNIT;
								}else{
									binder.obj[binder.field] = "";
								}
							}
							
							binder = $itfreer_core.getBinder(scope, scope.selectedRow);
							if (binder != null) {
								binder.obj[binder.field] = record;
							}
						});
					};
					if(onlySelectLeaf){
						options.onBeforeSelect = function(record){
							var tree = $(this).tree;
							var isLeaf = tree('isLeaf', record.target);
							if(!isLeaf)
							{
								//$.messager.show({
								//	msg: '请选择叶子节点！'
								//});
								// 返回false表示取消本次选择操作
								return false;
							}
						}
					}
				}
				options['onBeforeExpand'] = function(row) {
					var id = row[attrs.idField];
					var pTree = element.combotree('tree');
					var nodes = [];
					try {
						nodes = pTree.tree('getChildren', row.target);
					} catch (e) {
					}
					var currtJB = row[jbField];
					if(allLoadJB == currtJB){
						return;
					}
					if (nodes == null || nodes.length <= 0) {
						$itfreerHttp.getTreeData(attrs.tableName, {}, order, id, '',domainName, -1,
								-1, true, function(treedata) {
									if (treedata == null || treedata.length <= 0) {
										// 最后一个节点
										row.state = 'open';
									} else {
										pTree.tree('append', {
											parent : row.target,
											data : treedata
										});
										pTree.tree('collapse', row.target);
										pTree.tree('expand', row.target);
									}
								}, function(ex) {
								});
					}
					return true;
				};

				options.onShowPanel = function () {
					if (!isLoaded && delay ==true && !attrs.parentField) {
						loadData();
					};
				};

				options.onLoadSuccess = function (data) {
					if(bindValue){
						element.combotree('setValue',bindValue);
					}else{
						element.combotree('setValue','');
						safeApply(scope,function() {
							ctrl.$setViewValue('');
						});
					}
					isLoaded = true;
				}
				
				var cm = element.combotree(options);

				$formObject.combotrees.push(cm);

				ctrl.$render = function() {
					var viewValue = ctrl.$viewValue ? ctrl.$viewValue : '';
					bindValue = viewValue;
					var opt = "setValue";
					if (multiple == true && viewValue.indexOf(',') != -1) {
						opt = "setValues";
						viewValue = viewValue.split(",");
					};
					element.combotree(opt, viewValue);
					if (!isLoaded && delay ==true && !attrs.parentField && ctrl.$viewValue) {
						loadData(function() {
							scope.$apply(function() {
								element.combotree(opt, viewValue);
							});
						});
					}else{
						element.combotree(opt, viewValue);
					}
				};

				if (attrs.dynamic == "true" && !attrs.parentField && delay != true) {
					loadData();
				}
				function loadData (afterDataLoaded) {
					$itfreerHttp.getTreeData(attrs.tableName, queryObject, order, pId, jbs,domainName,
						-1, -1, true, function(treedata) {
						element.combotree('loadData', treedata);
						if (afterDataLoaded && typeof afterDataLoaded ==="function") {
							afterDataLoaded();
						};
					}, function(ex) {
					});
				}
				//解决$digest already in progress
				function safeApply($scope, fn) {
				    ($scope.$$phase || $scope.$root.$$phase) ? fn() : $rootScope.$apply(fn);
				}
			}
		};
	});

	/**
	 * combotree控制器
	 */
	var agComboboxController = ['$scope','$attrs','$element','$itfreerHttp','$parse',
		function ($scope, $attr, $element, $itfreerHttp, $parse) {

		this.parentIdValue = null;
		this.parentCombo = null;

		if ($attr.parentCombo && $("#"+$attr.parentCombo)[0]) {
			this.parentCombo = $("#"+$attr.parentCombo);
			$scope[$attr.parentCombo] = $("#"+$attr.parentCombo);
		}
		var ctrl = this;
		var getIdValue = function () {
			var value = null;
			if (ctrl.parentCombo) {
				var parentData = ctrl.parentCombo.combobox('getData');
				var pValue = ctrl.parentCombo.combobox('getValue');
				var pIDField = ctrl.parentCombo.attr('id-Field');
				for (var i = 0; i < parentData.length; i++) {
					var record = parentData[i];
					if (pValue === record.id) {
						value = pIDField ? 
	 						(record[pIDField] ? record[pIDField] : record.attributes[pIDField]) : record.id;
	 					break;
					};
				};
			}
			return value;
		};
		//console.log(ctrl.parentCombo);
		if (!ctrl.parentCombo) {return;};
		$scope.$watch(function parentValueWatch(val) {
			var idValue = getIdValue();
			if (idValue !== ctrl.parentIdValue) {
				ctrl.parentIdValue = idValue;
				var filter = {};
				filter[$attr.parentField] = ctrl.parentIdValue || "-10000";
				$itfreerHttp.getDomains($attr.tableName, $attr.domainName,filter,$attr.addPinYin, function(data) {
					data = data ? data : [];
					if($attr.addspace){
							data.unshift({'id':'nullItem','text':'<空>'});
						}
					$element.combobox('loadData', data);
					var value = $element.combobox('getValue');
					var isExsit = false;
					for (var i = 0; i < data.length; i++) {
						if(data[i].id == value){
							isExsit = true;
							break;
						}
					};
					if (isExsit) {
						$element.combobox('clear');
						$element.combobox('select',value);
					}else{ 
						$element.combobox('select','');
						$element.combobox('clear'); 
					}
				}, function(ex) {
				});
			};
		});
	}];

	/**
	 * Combobox控件
	 */
	itfreerformcoreModule.directive('agCombobox', function($http, $itfreerHttp, 
			$parse, $itfreer_core, $formObject, $rootScope) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			template : '<select class="fore-common-select"></select>',
			scope : {
				data : "=",
				parentCombo : "@",
				textValue : "@",
				change :"&ngChange"
			},
			controller : agComboboxController,
			link : function(scope, element, attrs, ctrl) {
				var isLoaded = false;
				var multiple = attrs.multiple === "true" ? true : false;
				var options = {
					data : scope.data,
					valueField : 'id',
					textField : 'text',
					multiple : multiple,
					editable:false
				};
				options.onSelect = function(record) {
					var viewValue = record ? record.id : '';
					var text = record ? record.text : '';
					if (multiple == true && record) {
						viewValue = getEleValues();
					};
					if (record && record.id == "nullItem") {
						//如果选择为空值，不论多选还是单选，viewValue都为空
						viewValue = '';
						element.combobox('setValue', viewValue);
					};
					var binder = $itfreer_core.getBinder(scope, scope.textValue);
					if (binder != null) {
						binder.obj[binder.field] = text;
					}
					if(scope.change()){
						scope.change()(record);
					}
					scope.$apply(function() {
						ctrl.$setViewValue(viewValue);
					});
				};
				options.onUnselect = function(record) {
					if (multiple == true && record) {
						var viewValue = getEleValues();
						scope.$apply(function() {
							ctrl.$setViewValue(viewValue);
						});
					};
				};
				//获取下拉多选值
				function getEleValues () {
					var values = element.combobox('getValues');
					if (values) {
						if (values.length < 2) {
							//如果多选值只有一个或者没有，将数组改为字符串
							values = values[0] || '';
						}else{
							//当选择多个时去除选择中的空值
							for (var i = 0; i < values.length; i++) {
								if(values[i] == ''){
									values.remove(values[i]);
								}
							};
							//转换为字符串
							values = values.join();
						}
					};
					return values;
				}
				options.onShowPanel = function () {
					if (!isLoaded && attrs.delay =="true" && !attrs.parentField) {
						loadData();
					};
				};
				//数据加载成功时，触发此事件
				options.onLoadSuccess = function (data) {
					isLoaded = true;
					selectFirstRow();
					selectFirstRowBindBombobx();
					//解决$digest already in progress
					function safeApply($scope, fn) {
					    ($scope.$$phase || $scope.$root.$$phase) ? fn() : $rootScope.$apply(fn);
					}
					//默认选中第一行
					function selectFirstRow(){
						if(attrs.selectfirstrow){
							if(data && data[0]){
								
								safeApply(scope,function() {
									element.combobox('setValue', data[0]["id"]);
									ctrl.$setViewValue(data[0]["id"]);
								});
								
							}
						}
					}
					/**
					 * 如果是带有级联的，那么在父级控件上若果是默认选中第一行，child控件结果只有一条（县级用户）的时候才会默认
					 */
					function selectFirstRowBindBombobx(){
						if(attrs.parentCombo && scope[attrs.parentCombo] && scope[attrs.parentCombo].attr("selectFirstRow")){
							scope.$apply(function(){
								if(data &&  data["length"] == 1){
									element.combobox('setValue', data[0]["id"]);
									ctrl.$setViewValue(data[0]["id"]);
								}
							});
						}
					}
				};
				var cm = element.combobox(options);
				$formObject.comboboxs.push(cm);

				ctrl.$render = function() {
					var viewValue = ctrl.$viewValue ? ctrl.$viewValue : '';
					var opt = "setValue";
					if (multiple == true && viewValue.indexOf(',') != -1) {
						opt = "setValues";
						viewValue = viewValue.split(",");
					};
					if (!isLoaded && attrs.delay =="true" && !attrs.parentField && ctrl.$viewValue) {
						loadData(function() {
							scope.$apply(function() {
								element.combobox(opt, viewValue);
							});
						});
					}else{
						element.combobox(opt, viewValue);
						//viewValue 为 ''  说明是新增或者清空当前选项
						if(attrs.selectfirstrow && !viewValue){
							loadData();
						}
					}
				};
				//初始化动态加载下拉数据
				if (attrs.dynamic == "true" && !attrs.parentField && attrs.delay !="true") {
					loadData();
				}
				//加载下拉数据
				function loadData (afterDataLoaded) {
					var addSpaceItem = attrs.addspace == "true";
					var filter = attrs.initFilter ? attrs.initFilter : null;
					$itfreerHttp.getDomains(attrs.tableName, attrs.domainName,filter,attrs.addPinYin, function(
							data) {
						data = data ? data : [];
						if(addSpaceItem){
							data.unshift({'id':'nullItem','text':'<空>'});
						}
						element.combobox('loadData', data);
						if (afterDataLoaded && typeof afterDataLoaded ==="function") {
							afterDataLoaded();
						};
					}, function(ex) {
					});
				};
				
//				scope.$watch(scope.data,function(){
//					alert("改变啦");
//				});
				
				if (attrs.defvalue != null && ctrl.$viewValue == null) {
					if(attrs.defvalue=="{userid}"){
						var userID = $itfreer_core.getCookie("userid");
						element.combobox('setValue', userID);
					} else {
						element.combobox('setValue', attrs.defvalue);
					}
				}
			}
		};
	});
	/**
	 * Treegrid控件
	 */
	itfreerformcoreModule.directive('agTreegrid', function($http, $itfreerHttp, $formObject) {
		return {
			replace : true,
			restrict : 'E',
			template : '<table></table>',
			scope : {
				queryObject : "@",
				filterValue : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				var options = {};
				options.columns = [];
				var obj = eval(attrs.columns);
				var checkboxFormatter = function(value,rowData,rowIndex){
					var cboxId = attrs.id + "_"+ rowData[attrs.idField];
					return "<input type='checkbox' name='" + attrs.id + "' id='" + cboxId + "'></input> " + value;
				};
				
				obj.forEach(function(item){
					if(item.hasOwnProperty("showCheckbox")
							&& item["showCheckbox"]==true
							&& !item.hasOwnProperty("formatter"))
					item.formatter = checkboxFormatter;
				});
				
				options.columns.push(obj);
				options.idField = attrs.idField;
				options.treeField = attrs.treeField;
				if (attrs.dynamic == "false" && attrs.formname) {
					options['onSelect'] = function(row) {
						scope.$apply(function() {
							scope.setEditRow(attrs.formname, row);
						});
					};
				}
				options['onBeforeExpand'] = function(row) {
					var id = row[attrs.idField];
					var nodes = element.treegrid('getChildren', id);
					if (nodes == null || nodes.length <= 0) {
						if(attrs.formname){
							$itfreerHttp.getTreeData(scope.formObject[attrs.formname].tableName, scope.formObject[attrs.formname].queryObject,
									scope.formObject[attrs.formname].orderObject, id, scope.formObject[attrs.formname].treeLoadJBs,'', 
									scope.formObject[attrs.formname].pageSize, scope.formObject[attrs.formname].pageIndex, false,
									function(treedata) {
										if (treedata == null || treedata.length <= 0) {
											// 最后一个节点
											row.state = 'open';
											element.treegrid('refresh', id);
											// 同步更新数据库
											row[scope.treeIsChildField] = "1";
											$itfreerHttp.save(scope.tableName, row, function(
													data) {
											}, function(ex) {
											});
										} else {
											element.treegrid('append', {
												parent : id,
												data : treedata
											});
											element.treegrid('refresh', id);
											element.treegrid('expand', id);
										}
									}, function(ex) {
							});
						}
					}
					return true;
				};
				var tg = element.treegrid(options);
				$formObject.treegrids.push(tg);

				if (attrs.dynamic == "true") {
					var tableName = attrs.tableName;

					var orderObjectEx = {};
					var msgs = attrs.orderObject.split(":");
					if(msgs.length==2){
						orderObjectEx[msgs[0]] = msgs[1];
					}else{
						orderObjectEx[orderField] = 0;
					}
					
					var queryObj = {};
					if(scope.queryObject){
						queryObj = scope.queryObject;
					}
					
					$itfreerHttp.getTreeData(tableName, queryObj, orderObjectEx, '', '','',
						scope.pageSize, scope.pageIndex, false, function(data) {
							element.treegrid('loadData', data);
						}, function(ex) {

					});
				}
				
//				scope.$watch(scope.queryObject,function(newVal){
//					var tableName = attrs.tableName;
//
//					var orderObjectEx = {};
//					var msgs = attrs.orderObject.split(":");
//					if(msgs.length==2){
//						orderObjectEx[msgs[0]] = msgs[1];
//					}else{
//						orderObjectEx[orderField] = 0;
//					}
//					
//					$itfreerHttp.getTreeData(tableName, scope.queryObject, orderObjectEx, '', '','',
//						scope.pageSize, scope.pageIndex, false, function(data) {
//							element.treegrid('loadData', data);
//						}, function(ex) {
//
//					});
//				});
				
				// element.treegrid('reload');
			}
		};
	});

	/**
	 * Datebox控件
	 */
	itfreerformcoreModule.directive('agDatebox', function($http, $itfreerHttp, $formObject, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			template : "<input></input>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var showCurDay = attrs.showCurday;
				var addDays=attrs.addDays;
				var options = {
					formatter : $itfreer_core.formatDate,
					editable : false
				};
				options['onSelect'] = function(date) {
					scope.$apply(function() {
						ctrl.$setViewValue($itfreer_core.formatDate(date));
					});
				};
				var db = element.datebox(options);
				$formObject.dateboxs.push(db);

				ctrl.$render = function() {
					if(typeof(ctrl.$viewValue) == "undefined" && showCurDay == "true"){
						var date = new Date();
						if(addDays!=null && addDays!="undefined" && addDays!=""){
							var day=date.getDate();
							var dayTime="";
							dayTime=Number(day)+Number(addDays);
							date.setDate(dayTime);
						}
			       		element.datebox('setValue', $itfreer_core.formatDate(date));
			       		ctrl.$setViewValue($itfreer_core.formatDate(date));
					}else{
						element.datebox('setValue', $itfreer_core.getDateObject(ctrl.$viewValue));
					}
				};
			}
		};
	});
	/**
	 * Datetimebox控件
	 */
	itfreerformcoreModule.directive('agDatetimebox', function($http, $itfreerHttp, $formObject, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			template : "<input></input>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var showCurDay = attrs.showCurday;
				var addDays=attrs.addDays;
				var options = {
					// formatter : $itfreer_core.formatDate,
					editable : false,
					showSeconds:false
				};
				options['onSelect'] = function(date) {
					scope.$apply(function() {
						var time=element.datetimebox('spinner').spinner('getValue');
						var dt = date.getFullYear()+'-'+ (date.getMonth()+1) +'-'+date.getDate()+' '+ time;
						element.datetimebox('setText',dt);
						element.datetimebox('hidePanel');
						ctrl.$setViewValue(dt);
					});
				};

				var db = element.datetimebox(options);

				$formObject.datetimeboxs.push(db);

				ctrl.$render = function() {
					if(typeof(ctrl.$viewValue) == "undefined" && showCurDay == "true"){
						var date = new Date();
						if(addDays!=null && addDays!="undefined" && addDays!=""){
							var day=date.getDate();
							var dayTime="";
							dayTime=Number(day)+Number(addDays);
							date.setDate(dayTime);
						}
			       		element.datetimebox('setValue', $itfreer_core.formatDate(date));
			       		ctrl.$setViewValue($itfreer_core.formatDate(date));
					}else{
						element.datetimebox('setValue', $itfreer_core.getDateObject(ctrl.$viewValue));
					}
				};
			}
		};
	});

	/**
	 * Textarea控件
	 */
	itfreerformcoreModule.directive('agTextarea', function($http, $itfreerHttp) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			template : "<textarea></textarea>",
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var name = attrs['name'];
				var elementName = "textarea[name='" + name + "']";
				var editor = null;
				KindEditor.ready(function(K) {
					editor = K.create(elementName, {
						uploadJson : getBasePath() + '/kindeditor/upload.do?sessionId='+sessionId,
						fileManagerJson : getBasePath() + '/kindeditor/fileManager.do?sessionId='+sessionId,
						allowFileManager : true,
						afterChange : function() {
							scope.$apply(function() {
								ctrl.$setViewValue(editor.html());
							});
						}
					});
				});

				ctrl.$render = function() {
				    if(!editor)
				      return;
					if (ctrl.$viewValue == null) {
						editor.html('');
					} else {
						editor.html(ctrl.$viewValue);
					}
				};
			}
		};
	});

	/**
	 * Upload控件
	 */
	itfreerformcoreModule.directive('agUpload', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var downloadUrl = getBasePath()+'/plupload/download.do';
				var isEnabled = attrs.isEnabled;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
					
				
				var uploadHtml ='';
				uploadHtml ='<div>'
					 + '<input type="button" flag="'+isEnabled+'"'
					 + ' class="zs-btn" value="'+btnLable+'"/>'
					 + '</div>';
				var filters = attrs.extensions ? [{title : "文档", extensions : attrs.extensions}]:[
							{title : "所有文档", extensions : "*"}
						];
				
				var html = '<div></div>'
					 + uploadHtml
					 +'<div class="zs-file-list"><ul></ul></div>';

				var el = document.createElement("div");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _listEl = el.lastChild.firstChild;
				var _btnEl = _winEl.nextSibling.lastChild;
				var _valueEl = el.lastChild.firstChild;
				// element.html(templateString);
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				//删除按钮效果
				$(_listEl).on("mouseenter","li",function(){
					$(this).find("i a").css(mouseenterCss);
				}).on("mouseleave","li",function(){
					$(this).find("i a").css( {"display":"inline-block"});
				}).on('click', 'li i a', function(){
					//绑定删除事件
					_onDelFile(this);
				});
				
				$(_winEl).window({   
					title:'上传文件',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
					});
				
				var fileList = [];
				var errors = [];

				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
					+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'html5,flash,gears,browserplus,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName + ":" + file.name;
										_addFileListItem(fileInfo);
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										if(onUploadFn){
											scope.$apply(function() {
												onUploadFn(scope,{file:fileInfo});	
											});
										}
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}

				//添加到文件列表
				function _addFileListItem (fileInfo) {
					if (!fileInfo) return;
					fileInfoArr = fileInfo.split(":");
					var url = fileInfoArr[0];
					var name = fileInfoArr[1];
					fileList.push(fileInfo);
					var _index = fileList.indexOf(fileInfo);
					var xel ='';
					xel = '<i><a docIndex="'+_index+'" ></a></i>';
					var _downloadUrl = downloadUrl+"?filePath="+url.replace(getBasePath()+"/","")+"&fileName="+encodeURIComponent(name);
					//1024分辨率下控制文件的名字长度为 14 个中文字符的长度，超过后以...显示名称
					var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">'+name+'</a>'+xel+'</li>').appendTo($(_listEl));
					//{{}}有时会出现错乱的问题，页面输出{{name}}
					//var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">{{"'+name+'" | asLength:20}}</a>'+xel+'</li>').appendTo($(_listEl));
					$fileLi = $compile($fileLi)(scope);
					_rebuildValue();
				}
				//重新赋值
				function _rebuildValue () {
					var fileString = fileList.join("|");
					$(_valueEl).val(fileString);
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileString);
						});
					}
				}

				function _onDelFile (target) {
					$.messager.confirm('确认操作', '确定要删除这个文件吗？', function(action){
						if (action){
						    var $fileLi = $(target).closest('li').hide();
							var docIndex = $(target).attr('docIndex');
							$fileLi.remove();
							//从列表中删除
							fileList.splice(docIndex,1);
							_rebuildValue();
						}
					});
				}
				
				ctrl.$render = function() {
					//删除文件列表
					fileList = [];
					$(_listEl).empty();
					if (!ctrl.$viewValue) {
						$(_valueEl).val("");
					} else {
						var fileInfo = ctrl.$viewValue.split("|");
						for (var i = 0; i < fileInfo.length; i++) {
							_addFileListItem(fileInfo[i]);
						};
					}
				};
			}
		};
	});

	/**
	 * Upload1控件
	 */
	itfreerformcoreModule.directive('agUpload1', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var downloadUrl = getBasePath()+'/plupload/download.do?sessionId='+sessionId;
				var isEnabled = attrs.isEnabled;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
				
				
				var uploadHtml ='';
				uploadHtml ='<div style="float:right">'
					+ '<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+btnLable+'</a>'
					+ '</div>';
				var filters = attrs.extensions ? [{title : "文档", extensions : attrs.extensions}]:[
				                                                                                  {title : "所有文档", extensions : "*"}
				                                                                                  ];
				
				var html = '<div></div>'
					+ uploadHtml
					+'<div style="float:left" class="zs-file-list"><ul></ul></div>';
				
				var el = document.createElement("div");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _listDiv = el.lastChild;
				var _listEl = el.lastChild.firstChild;
				var _btnEl = _winEl.nextSibling.lastChild;
				var _valueEl = el.lastChild.firstChild;
				// element.html(templateString);
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				//删除按钮效果
				$(_listEl).on("mouseenter","li",function(){
					$(this).find("i a").css(mouseenterCss);
				}).on("mouseleave","li",function(){
					$(this).find("i a").css( {"display":"none"});
				}).on('click', 'li i a', function(){
					//绑定删除事件
					_onDelFile(this);
				});
				
				$(_winEl).window({   
					title:'上传文件',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
				});
				
				var fileList = [];
				var errors = [];
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
							+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName + ":" + file.name;
										_addFileListItem(fileInfo);
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										if(onUploadFn){
											scope.$apply(function() {
												onUploadFn(scope,{file:fileInfo});	
											});
										}
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}
				
				//添加到文件列表
				function _addFileListItem (fileInfo) {
					if (!fileInfo) return;
					fileInfoArr = fileInfo.split(":");
					var url = fileInfoArr[0];
					var name = fileInfoArr[1];
					fileList.push(fileInfo);
					var _index = fileList.indexOf(fileInfo);
					var xel ='';
					xel = '<i><a docIndex="'+_index+'" ></a></i>';
					var _downloadUrl = downloadUrl+"?filePath="+url.replace(getBasePath()+"/","")+"&fileName="+encodeURIComponent(name);
					if($(_listDiv).find("label"))
						$(_listDiv).find("label").remove();
					
					//1024分辨率下控制文件的名字长度为 14 个中文字符的长度，超过后以...显示名称
					var $fileLi = $('<li><a href="'+_downloadUrl+'" title="'+name+'">{{"'+name+'" | asLength:20}}</a>'+xel+'</li>').appendTo($(_listEl));
					$fileLi = $compile($fileLi)(scope);
					_rebuildValue();
				}
				//重新赋值
				function _rebuildValue () {
					var fileString = fileList.join("|");
					$(_valueEl).val(fileString);
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileString);
						});
					}
				}
				
				function _onDelFile (target) {
					$.messager.confirm('确认操作', '确定要删除这个文件吗？', function(action){
						if (action){
							var $fileLi = $(target).closest('li').hide();
							var docIndex = $(target).attr('docIndex');
							$fileLi.remove();
							//从列表中删除
							fileList.splice(docIndex,1);
							if(fileList.length==0  && $(_listDiv).find("label").length==0){
								$("<label>无</label>").appendTo($(_listDiv));
							}
							_rebuildValue();
						}
					});
				}
				
				ctrl.$render = function() {
					//删除文件列表
					fileList = [];
					$(_listEl).empty();
					if (!ctrl.$viewValue) {
						$(_valueEl).val("");
						if(fileList.length==0 && $(_listDiv).find("label").length==0){
							$("<label>无</label>").appendTo($(_listDiv));
						}
					} else {
						if($(_listDiv).find("label"))
							$(_listDiv).find("label").remove();
						var fileInfo = ctrl.$viewValue.split("|");
						for (var i = 0; i < fileInfo.length; i++) {
							_addFileListItem(fileInfo[i]);
						};
					}
				};
			}
		};
	});
	/**
	 * Upload Image控件
	 */
	itfreerformcoreModule.directive('agUploadImage', function($parse, $itfreerHttp,$compile) {
		var sessionId = $("#_sessionid").html();
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var btnLable = attrs.btnLable ? attrs.btnLable : "上传";
				var delLable = attrs.delLable ? attrs.delLable : "删除";
				var noImage = attrs.noImage ? attrs.noImage : "";
				var isEnabled = attrs.isEnabled;
				var downloadUrl = getBasePath()+'/plupload/download.do?sessionId='+sessionId;
				//定义鼠标移动到列表时的css效果
				var mouseenterCss = {"display":"inline-block"};
				if( typeof(isEnabled) == 'undefined' || isEnabled == ''){
					mouseenterCss = {"display":"inline-block"};
				}else{
					scope.$watch(isEnabled,function(newVal){
						if(newVal){
							mouseenterCss = {"display":"inline-block"};
							$("[flag = '"+isEnabled+"']").show();
						}else{
							mouseenterCss = {"display":"none"};
							$("[flag = '"+isEnabled+"']").hide();
						}
					});
				}
				
				var uploadHtml ='';
				uploadHtml ='<div style="float: middle" flag="'+isEnabled+'">'
					+ '<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+btnLable+'</a>'
					+ '&nbsp;&nbsp;<a style="cursor: pointer;text-decoration:underline;color:blue;" flag="'+isEnabled+'">'+delLable+'</a>'
					+ '</div>';
				var filters =  [{title : "图片", extensions : "jpg,png"}];
				
				var html = '<div></div>'
					+'<div><img onclick="imgShow($(this))" width="100px" height="100px" src="'+noImage+'"/></div>'
					+ uploadHtml;
				
				var el = document.createElement("div");
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _btnEl = el.lastChild.firstChild;
				var _delEl = el.lastChild.lastChild;
				var _imageEl = _winEl.nextSibling.lastChild;
				
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});
				$(_delEl).click(function(){
					_delImageSrc(this);
				});
				
				$(_winEl).window({   
					title:'选择图片',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:400,
					modal:true,
					onOpen:init_uploader
				});
				
				var fileList = [];
				var errors = [];
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploader")[0]) {
						$("#uploader").remove();
					};
					$(_winEl).append('<div id="uploader"><p>您的浏览器未安装 Flash, '
							+'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploader").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/plupload/upload.do?sessionId='+sessionId,
						max_file_size : maxSize+'mb',
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						// Specify what files to browse for
						filters : filters,
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										var fileInfo = rs.newName;
										_updateImageSrc(fileInfo);
									}else{
										errors.push(file.name);
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploader").remove();
								$(_winEl).window('close');
							}
						}
					});
				}
				
				//更新Image Src
				function _updateImageSrc (fileInfo) {
					if (!fileInfo) return;
					var newFileInfo = fileInfo.split(":")[0];
					
					var _downloadUrl = "../"+newFileInfo.replace(getBasePath()+"/","");
					$(_imageEl).attr("src",_downloadUrl);//+Math.random()
					
					if(!scope.$$phase){
						scope.$apply(function () {
							ctrl.$setViewValue(fileInfo);
						});
					}
				}
				
				//删除图片
				function _delImageSrc (target) {
					$.messager.confirm('确认操作', '确定要删除图片吗？', function(action){
						if (action){
							$(_imageEl).attr("src",noImage);
							
							if(!scope.$$phase){
								scope.$apply(function () {
									ctrl.$setViewValue("");
								});
							}
						}
					});
				}
				
				ctrl.$render = function() {
					if (!ctrl.$viewValue) {
						$(_imageEl).attr("src",noImage);
					} else {
						var fileInfo = ctrl.$viewValue;
						_updateImageSrc(fileInfo);
					}
				};
			}
		};
	});
	/**
	 * 控件隐藏时验证不可用
	 */
	itfreerformcoreModule.directive('hideNovalidate', function($http, $itfreerHttp) {
		var sessionId = $("#_sessionid").html();
		return {
			require: ['ngModel','^form'],
			restrict : 'A',
			link : function(scope, element, attrs,ctrls) {
				var modelCtrl = ctrls[0];
				var formCtrl = ctrls[1];
				if (!formCtrl) return;

				scope.$watch(function getDisplay() {
					return scope.$eval(attrs.hideNovalidate);
				},function ngShowWatch(val) {
			        if (!val) {
			        	//控件隐藏,从表单控制器中删除
						formCtrl.$removeControl(modelCtrl);
			        }else{
			        	//控件显示,添加到表单控制器,并根据控件验证状态修改表单表单验证状态
			        	formCtrl.$addControl(modelCtrl);
						angular.forEach(modelCtrl.$error, function(validity, validationKey) {
							formCtrl.$setValidity(validationKey, !validity, modelCtrl);
						});
			        }
				});
			}
		};
	});

	/**
	 * Excel导入
	 */
	itfreerformcoreModule.directive('agImpexcel', function($http, $parse, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			link : function(scope, element, attrs, ctrl) {
				var btnclass = attrs.btnclass ? attrs.btnclass : "zs-btn";
				var html = "<div></div> " +
						"<input type='button' class='" +btnclass+"' value='"+attrs.btntext+"' />";

				var el = document.createElement("span");
				// el.className = "fore-sys-file-upload";
				el.innerHTML = html;
				var _winEl = el.firstChild;
				var _btnEl = el.lastChild;
				element.html(el);
				
				$(_btnEl).click(function(){
					$(_winEl).window('open');
				});

				$(_winEl).window({   
					title:'Excel导入',
					minimizable:false,
					collapsible:false,
					shadow:true,
					maximizable:false,
					closed:true,
					width:600,    
					height:310,
					modal:true,
					onOpen:init_uploader
					});
				
				var maxSize = attrs.maxSize ? attrs.maxSize : "200";
				var files = [];
				var errors = [];
				var fileObject = {};
				
				//初始化上传控件
				function init_uploader () {
					if ($("#uploaderExcel")[0]) {
						$("#uploaderExcel").remove();
					};
					$(_winEl).append('<div id="uploaderExcel"><p>您的浏览器未安装 Flash, ' +'Gears, BrowserPlus 或者支持 HTML5。</p></div>');
					$("#uploaderExcel").pluploadQueue({
						// General settings
						runtimes : 'gears,flash,browserplus,html5,html4',
						url : getBasePath()+'/excelplupload/upload.do?excelid='+attrs.excelid,
						max_file_size : maxSize+'mb',
						unique_names:true,
						unique_names : true,
						multiple_queues : true,
						chunk_size: '512kb',
						multi_selection: false,
						// Specify what files to browse for
						filters : [
							{title : "Excel", extensions : "xls,xlsx"}
						],
						// Flash settings
						flash_swf_url : getJsBasePath()+'/style/script/plupload/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/style/script/plupload/Moxie.xap',
						/*flash_swf_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.swf',
						silverlight_xap_url : getJsBasePath()+'/plupload/v2.1.4/Moxie.xap',*/
						init:{
							FileUploaded:function(uploader,file,response){
								if(response.response){
									var rs = $.parseJSON(response.response);
									if(rs.status){
										files.push(file.name);
										fileObject = rs.resultObject;
										
										var onUploadFn = null;
										if(attrs.hasOwnProperty("onUploaded") && attrs.onUploaded && attrs.onUploaded!=""){
											onUploadFn = $parse(attrs.onUploaded);
										}
										
										var binder = $itfreer_core.getBinder(scope, attrs.editrow);
										if(onUploadFn){
											if(binder!=null){
												scope.$apply(function() {
													onUploadFn(scope,{file:fileObject,editrow:binder.obj[binder.field]});	
												});
											}else{
												scope.$apply(function() {
													onUploadFn(scope,{file:fileObject});	
												});
											}
										}
									}
								}
							},
							UploadComplete:function(uploader,fs){
								uploader.splice();//从上传队列中删除所有文件
								uploader.refresh();
								uploader.destroy();//ie9以下若不销毁此对象第二次上传会十分缓慢
								$("#uploaderExcel").remove();
								$(_winEl).window('close');
							},
							FilesAdded: function (up, files) {
							    $.each(up.files, function (i, file) {
							        if (up.files.length <= 1) {
							            return;
							        }
							        up.removeFile(file);
							    });
							}
						}
					});
				}
			}
		};
	});

	/**
	 * 默认选择人
	 */
	itfreerformcoreModule.directive('agUser', function($http, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			scope : {
				textValue : "@",
				canuse : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				
				var labelId = "label_"+attrs.id;
				var templateString = "<label id='"+labelId+"'></label>";
				element.html(templateString);
				
				scope.$watch(function(){
					setUser();
				});
				
				ctrl.$render = function() {
					setUser();
				};
				
				function setUser() {
					if (typeof(ctrl.$viewValue) == "undefined" || ctrl.$viewValue == null || ctrl.$viewValue == "") {
						if(scope.canuse=='true'){
							var userid = $itfreer_core.getCookie("userid");
							var userrealname = decodeURI(escape($itfreer_core.getCookie("username")));
							ctrl.$setViewValue(userid);
							$('#'+labelId).text(userrealname);
						}else{
							$('#'+labelId).text("");
						}
					} else {
						if(ctrl.$viewValue == "-1"){
							$('#'+labelId).text("超级管理员");
						}else{
							var userName = "";
							var binder = $itfreer_core.getBinder(scope, scope.textValue);
							if (binder != null) {
								userName = binder.obj[binder.field];
								userName = userName ? userName : '';
							}
							if(userName=="-1"){
								$('#'+labelId).text("超级管理员");
							}else{
								if(userName!=""){
									$('#'+labelId).text(userName);
								}
							}
						}
					}
				};
			}
		};
	});

	/**
	 * 默认时间
	 */
	itfreerformcoreModule.directive('agDate', function($http, $itfreerHttp, $itfreer_core) {
		return {
			replace : true,
			restrict : 'E',
			require : "ngModel",
			scope : {
				canuse : "@"
			},
			link : function(scope, element, attrs, ctrl) {
				
				var labelId = "label_"+attrs.id;
				var templateString = "<label id='"+labelId+"'></label>";
				element.html(templateString);
				
				scope.$watch(function(){
					setDate();
				});
				
				ctrl.$render = function() {
					setDate();
				};
				
				function setDate() {
					if (typeof(ctrl.$viewValue) == "undefined" || ctrl.$viewValue == null || ctrl.$viewValue == "") {
						if(scope.canuse=='true'){
							var date = new Date();
							var fmDate = formatDate(date);
				       		ctrl.$setViewValue(fmDate);
							$('#'+labelId).text(fmDate);
						}else{
							$('#'+labelId).text("");
						}
					} else {
						var fmDate = $itfreer_core.getDateObject(ctrl.$viewValue);
						$('#'+labelId).text(fmDate);
					}
				};
			}
		};
	});

	/**
	 * 具有打印功能的按钮
	 */
	itfreerformcoreModule.directive('agPrintButton', function($itfreer_form_core, $sce) {
		return {
			restrict : 'EA',
			template : '<input type="button" class="fore-common-btn" value="{{label}}">',
			scope: { 
				label : '@',		//按钮上显示的文字
				method : '@', 		//打印方式 html|table|template
				targetId : '@', 	//目标元素的id（method为template时不可用）
				taskName : '@', 	//打印任务名
				pageSize : '@', 	//纸张规格 A4|B5
				pageDirection : '@', //纸张方向 1:竖向 | 2:横向
				padding : '@'		//页边距，单位毫米。可以是一个值代表四个边距，也可以是“上,右,左,下”，也可以是“两边,上下” 
			},
			link : function(scope, element, attrs) {
				//纸张大小，每种纸张规格数组代表竖向放置时的[宽, 高]
				var PAGESIZE = {
					A4 : [210, 297],
					B5 : [182, 257]
				};
				var lodop = $itfreer_form_core.getLodop(),
					method = scope.method || 'html',
					taskName = scope.taskName || '打印任务',
					pageSize = setPageSize(scope.pageSize || 'A4'),
					pageDirection = setPageDirection(scope.pageDirection),
					padding = setPadding(scope.padding || "25,20,22,20");
				function setPageSize(pageSize) {
					pageSize = pageSize.toUpperCase();
					if(PAGESIZE[pageSize]){
						return pageSize;
					}else{
						console.warn('agPrintButton页面规格设置不正确，将使用默认配置:A4');
						return 'A4';
					}
				};
				function setPageDirection(pageDirection){
					var r = 1;
					switch(pageDirection){
						case '1': r = 1; break;
						case '2': r = 2; break;
						default : break;
					}
					return r;
				};
				function setPadding(padding) {
					var paddings = padding.split(',');
					for(var i=0; i<paddings.length; i++){
						paddings[i] = parseInt(paddings[i]);
					}
					if(paddings.length===1){
						return [paddings[0],paddings[0],paddings[0],paddings[0]];
					}else if(paddings.length===2){
						return [paddings[1],paddings[0],paddings[1],paddings[0]];
					}else if(paddings.length===4){
						return paddings;
					}else{
						console.warn('agPrintButton页边距设置不正确，将使用默认配置：[25,20,22,20]');
						return [25,20,22,20];
					}
				};
				element.on('click', function(event) {
					if (!lodop) {
						var url = navigator.userAgent.indexOf('Win64') >= 0 ?
							$itfreer_form_core.urls.lodopPlugin64 : $itfreer_form_core.urls.lodopPlugin32;
						var ele = document.createElement('div');
						ele.id = "lodopDownWin";
						$(ele).appendTo('body');
						$(ele).window({
							title : '请安装打印控件',  
						    width:500,    
						    height:200,    
						    modal:true,
						    content:'<div style="width:400px;">'+
									'<p>您需要安装打印控件才能使用打印功能，请' + 
									'<a href="'+url+'" style="color:red">点击这里</a>下载打印控件并安装。</p>' + 
									'<p>安装成功后需<a href="'+location.href+'" style="color:red">刷新</a>页面。</p>' +
									'<p style="color:#777">提示：打印控件只需安装一次，支持IE（包括以IE为内核的各种国产浏览器）、'+
									'Chrome(33版本之前,后续chrome版本停止支持NPPlugin,打印控件暂不可用)、火狐、Safari以及Opera等各种主流浏览器。<br/>' +
									(navigator.userAgent.indexOf('Firefox') == -1 ? '' :
										'对于火狐浏览器，如曾安装过Lodop旧版附件npActiveXPLugin，请在【工具】->【附加组件】->【扩展】中先卸它。</p>') +
									'</div>'  
						});		
					}else{
						_previewPrint();
					}
				});
				function _previewPrint(){
					switch(method){
						case 'html' :
							_previewPrintHtml(false);
							break;
						case 'table' :
							_previewPrintHtml(true);
							break;
						case 'template' : 
							//TODO:模板方式打印
							break;
						default : 
							console.error('不支持的打印方式：'+method);
					}
				};
				function _previewPrintHtml(isTable){
					scope.$apply(function () {
						var target = document.getElementById(scope.targetId);
						var html = target ? target.outerHTML : '';
						lodop.PRINT_INIT(taskName);
						lodop.SET_PRINT_PAGESIZE (pageDirection, 0, 0, pageSize);
						var pageType = PAGESIZE[pageSize]
						var width = ((pageDirection==1 ? pageType[0] : pageType[1])- padding[1] - padding[3]) + 'mm';
						var height = ((pageDirection==1 ? pageType[1] : pageType[0])- padding[0] - padding[2]) + 'mm';
						var left = padding[3]+'mm';
						var top = padding[0]+'mm';
						if(isTable)
							lodop.ADD_PRINT_TABLE(top, left, width, height, html);
						else
							lodop.ADD_PRINT_HTM(top, left, width, height, html);
						lodop.PREVIEW();
					});
				}
			}
		};
	});

	/**
	 * 获取焦点
	 */
	itfreerformcoreModule.directive('agFocus', function($document) {
	    return function(scope, element, attrs) {
	        $(element).bind('focus', function(e){
	            scope.$apply(attrs.agFocus);
	        });
	    };
	});

	/**
	 * 获取焦点
	 */
	itfreerformcoreModule.directive('itfreerWindow', function($document, $formObject) {
	    return function(scope, element, attrs) {
	        var title = "编辑";
			if(attrs.title){
				title = attrs.title;
			}

			var width = 800;
			if(attrs.width){
				width = parseInt(attrs.width);
			}

			var height = 400;
			if(attrs.height){
				height = parseInt(attrs.height);
			}
			var destroy = function(){
				alert('aa');
			};
			
			//存在相同的id，先删除，再添加
			for(var i=0;i<$formObject.windows.length;i++){
				if($formObject.windows[i].attr('id')==element.attr('id')){
					$formObject.windows[i].window('destroy');
					$formObject.windows.splice(i,1);
					break;
				}
			}

			var pw = $(element).window({
				iconCls:'icon-edit',
				modal:true,
				closed:true,
				minimizable:false,
				collapsible:false,
				shadow:true,
				maximizable:false,
				resizable:false,
			    title: title,
			    width: width,
			    height: height
			});
			$formObject.windows.push(pw);
	    };
	});

	/**
	 * 下拉菜单
	 */
	itfreerformcoreModule.directive('itfreerSplitbutton', function($document) {
	    return function(scope, element, attrs) {
	        $(element).splitbutton({menu:'#'+attrs.mid});
	    };
	});

	// 异步加载指今
	itfreerformcoreModule.directive('agInclude', 
		['$http', '$templateCache', '$anchorScroll', '$animate', '$sce', 
		function($http,$templateCache,$anchorScroll,$animate,$sce) {
		    return {
			    restrict: 'ECA',
			    priority: 400,
			    terminal: true,
			    transclude: 'element',
			    controller: angular.noop,
			    compile: function(element, attr) {
			      	var srcExp = attr.ngInclude || attr.src,
			          	onloadExp = attr.onload || '',
			          	autoScrollExp = attr.autoscroll;

			      	return function(scope, $element, $attr, ctrl, $transclude) {
				        var changeCounter = 0,
				            currentScope,
				            previousElement,
				            currentElement;

			        	var cleanupLastIncludeContent = function() {
					        if(previousElement) {
					            previousElement.remove();
					            previousElement = null;
					        }
					        if(currentScope) {
					            currentScope.$destroy();
					            currentScope = null;
					        }
					        if(currentElement) {
					            $animate.leave(currentElement, function() {
					              previousElement = null;
					            });
					            previousElement = currentElement;
					            currentElement = null;
					        }
			        	};

				        scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
					        var afterAnimation = function() {
					            if (autoScrollExp && (!autoScrollExp || scope.$eval(autoScrollExp))) {
					              $anchorScroll();
					            }
					        };
					        var thisChangeId = ++changeCounter;
					        if (src) {
					            $http.get(src, {cache: $templateCache}).success(function(response) {
						            if (thisChangeId !== changeCounter) return;
						            var newScope = scope.$new();
						            ctrl.template = response;

						            var clone = $transclude(newScope, function(clone) {
						                cleanupLastIncludeContent();
						                $animate.enter(clone, null, $element, afterAnimation);
						            });

						            currentScope = newScope;
						            currentElement = clone;

						            currentScope.$emit('$includeContentLoaded');
						            scope.$eval(onloadExp);
					            }).error(function() {
					              	if (thisChangeId === changeCounter) cleanupLastIncludeContent();
					            });
					            scope.$emit('$includeContentRequested');
					        } else {
					            cleanupLastIncludeContent();
					            ctrl.template = null;
					        }
				        });
			      	};
			    }
			};
		}]
	);

	// 异步加载指今
	itfreerformcoreModule.directive('agInclude', 
		['$compile', '$sce', function($compile, $sce) {
		    return {
		      	restrict: 'ECA',
		      	priority: -400,
		      	require: 'agInclude',
		      	link: function(scope, $element, $attr, ctrl) {
		      		scope.totalCart = function() {
					    return $attr.show;
					};
		      		scope.$watch(scope.totalCart, function(){
						if($attr.show && $attr.show=='true'){
							if($element.context.innerText.length<=0){
								$element.html(ctrl.template);
			        			$compile($element.contents())(scope);
							}
			      		}
					});
		      	}
		    };
		}]
	);

	/**
	 * 附件显示
	 */
	itfreerformcoreModule.filter("asFiles", ['$sce', function ($sce) {
		return function (input) {
	    	var msgs = input.split("|");
	    	var result = "";
	    	msgs.forEach(function(item){
	    		var fileItems = item.split(":");
	    		result += "<a title='"+fileItems[1]+"' href='"+fileItems[0]+"'>"+fileItems[1]+"</a> ";
	    	});
	    	return $sce.trustAsHtml(result);
	    };
	}]);

	/* 
	 * 当前流程审批用户
	 */
	itfreerformcoreModule.filter("asBpmUsers", function () {
	    return function (input) {
	    	if(input==null || input==""){
	    		return "";
	    	}
	    	var tasks = input.split(":");
	    	if(tasks.length==1){
	    		var users = tasks[0].split(",");
	            var userReturn = "";
	            for(var i=2; i<users.length; i+=2){
	            	userReturn += users[i+1] + ",";
	            }
	            userReturn = userReturn.substring(0, userReturn.length-1);
	            return userReturn;
	    	} else {
	    		var userReturn = "";
	    		for(var j=0; j<tasks.length; j++){
	    			var users = tasks[j].split(",");
	    			userReturn += users[1] + "(";
	                for(var i=2; i<users.length; i+=2){
	                	userReturn += users[i+1] + ",";
	                }
	                userReturn = userReturn.substring(0, userReturn.length-1) + "),";
	            }
	    		userReturn = userReturn.substring(0, userReturn.length-1);
	            return userReturn;
	    	}
	    };
	});

	/* 
	 * 加载服务器
	 */
	itfreerformcoreModule.run(function($rootScope, $itfreerHttp, $itfreer_form_core, $formObject) {
	  	
	});
}(window, angular));